@plot-pm/board 0.21.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/plot-host.sh CHANGED
@@ -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,36 @@
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).
438
+ # issue-list --title-has <text> keeps open issues whose title contains <text>,
439
+ # combinable with --label (github only; exit 4 on
440
+ # Bitbucket and on Jira). GitHub's search is a
441
+ # complete answer within its own result count, so
442
+ # this never pages: `complete` reads false only
443
+ # where the result count reaches --limit.
372
444
  # issue-open <request-json> (jira)
373
445
  # issue-open <title> <body> [--label <label>...] (github-issues)
374
446
  # THE SECOND OF TWO WRITES TO A TRACKER: open
@@ -485,6 +557,17 @@
485
557
  # groups repeat statuses on one sha (this
486
558
  # estate's caller passes `plot/review`). A call
487
559
  # that reaches the API and fails exits 3.
560
+ # pr-comment <number> <body> [marker]
561
+ # Posts one comment on a PR's timeline through
562
+ # the signed-in CLI identity (`gh pr comment`),
563
+ # so it needs no `Review app` key. Keyed by PR
564
+ # number, not a sha. With a <marker>, edits the
565
+ # comment holding it, else posts. A call that
566
+ # reaches the GitHub API and fails exits 3. EXIT 4 on
567
+ # Bitbucket: the bb CLI this script is written
568
+ # against documents no write to a PR's comment
569
+ # thread, and this op does not guess at an
570
+ # unverified `bb api` POST.
488
571
  #
489
572
  # TRANSPORT IS NOT A CALLER'S CONCERN. Where a host offers a question over more
490
573
  # than one transport — GitHub's REST against its GraphQL — the choice is made
@@ -530,6 +613,10 @@ ISSUE_PAGE_ROWS=100
530
613
  # that failed, as opposed to exit 4 (cannot be asked) or an answered empty list.
531
614
  # An empty message or a recognised lookup miss is an answer; anything else exits 3.
532
615
  miss_or_exit3() { [ -z "$1" ] || is_lookup_miss "$1" || { echo "plot-host: $1" >&2; exit 3; }; }
616
+ # `pr-merged`'s own third value for a failed call: a lookup miss still means
617
+ # not-merged, anything else prints the host's words and answers `unknown`
618
+ # rather than exiting — the caller already branches on this word, not a code.
619
+ miss_or_unknown() { if [ -z "$1" ] || is_lookup_miss "$1"; then echo "not-merged"; else echo "plot-host: $1" >&2; echo "unknown"; fi; }
533
620
  gh_fail() { echo "plot-host: $(cat "$HOST_ERR" 2>/dev/null)" >&2; rm -f "$HOST_ERR"; exit 3; }
534
621
 
535
622
  # Exit 3 — reserved for "the op itself cannot proceed", distinct from `die`'s
@@ -548,6 +635,14 @@ CHECKS_OF='def ck: (.conclusion // "") as $k | (.status // "") as $s | (if $s !=
548
635
  def checks_of: if (.statusCheckRollup|length) == 0 then "none" elif any(.statusCheckRollup[]; ck == "bad") then "failing"
549
636
  elif any(.statusCheckRollup[]; ck == "wait") then "pending" else "green" end;'
550
637
 
638
+ # THE ONE FOLD of a PR's mergeability into a word, for `pr-list --rich` and both
639
+ # `pr-state` transports. GraphQL says `mergeable` CONFLICTING|MERGEABLE|UNKNOWN
640
+ # and `mergeStateStatus` DIRTY; REST's single-PR payload says `mergeable`
641
+ # true|false|null and `mergeable_state` dirty. REST's list payload carries
642
+ # neither, so a `pr-state` asked by branch over REST reads `unknown`.
643
+ MERGEABLE_OF='def mergeable_of: if .mergeable == "CONFLICTING" or .mergeable == false or .mergeStateStatus == "DIRTY" or .mergeable_state == "dirty" then "conflicting"
644
+ elif .mergeable == "MERGEABLE" or .mergeable == true then "mergeable" else "unknown" end;'
645
+
551
646
  # Exit 5 — the host refused to answer FOR NOW. A rate limit, primary or
552
647
  # secondary: nothing is broken, nothing needs fixing, and the same question
553
648
  # asked later will be answered.
@@ -814,9 +909,18 @@ PR_LIST_PARTIAL_RC=7
814
909
  # TWO VARIADIC LISTS, ONE `"$@"`. The host command and the jq arguments are
815
910
  # both open-ended, and bash has one positional array — so the jq side travels
816
911
  # in this global, set by the caller immediately before the call. It is read
817
- # once per state and never written here.
912
+ # once per state and never written here, UNLESS `PR_LIST_BIND_FN` names a
913
+ # function that recomputes it — see below.
818
914
  PR_LIST_JQ_ARGS=()
819
915
 
916
+ # The name of a function to call with this state's raw rows ($1) right before
917
+ # they are piped through `jq_prog`, or empty to skip it (every existing
918
+ # caller's behaviour). Runs INSIDE the one per-state loop below rather than a
919
+ # second walk, because the Jenkins sha-bind needs each state's own rows and
920
+ # `pr_list_states` is the one place that holds them before they are consumed.
921
+ # Set and cleared by the caller, same as `PR_LIST_JQ_ARGS`.
922
+ PR_LIST_BIND_FN=""
923
+
820
924
  # --- the per-branch sweep (#333) --------------------------------------------
821
925
  #
822
926
  # THE JOIN ASKS ABOUT BRANCHES AND THE LIST ANSWERS ABOUT A REPOSITORY, and the
@@ -972,6 +1076,13 @@ bb_branch_query() { # $1=branch $2=adapter state; rest=global bb args → values
972
1076
  printf '%s' "$_out" | jq -c '.values // []'
973
1077
  }
974
1078
 
1079
+ # A FULL `bb_branch_query` PAGE WITH NO MATCHING ROW CANNOT PROVE ABSENCE.
1080
+ # $1=the JSON array, $2=a jq `any(.[]; …)` predicate naming the field that
1081
+ # would carry the answer. True only at the 50-row ceiling with the predicate
1082
+ # finding nothing — the one condition `pr-merged`, `pr-merge-commit` and
1083
+ # `pr-merged-heads` each guard against before reading silence as a negative.
1084
+ bb_full_page_lacks() { [ "$(jq 'length' <<<"$1")" -ge 50 ] && ! jq -e "$2" >/dev/null 2>&1 <<<"$1"; }
1085
+
975
1086
  # Ask about EVERY tracked branch in one state, printing one combined array.
976
1087
  #
977
1088
  # THE SHAPE `pr_list_states` ALREADY EXPECTS. It calls its host command once
@@ -1161,7 +1272,13 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1161
1272
  #
1162
1273
  # ONE PAGE, AS BEFORE. 50 is the endpoint's `pagelen` ceiling and the limit
1163
1274
  # `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.
1275
+ # 50 most recent here too, and `pr_list_report_truncation` still says so —
1276
+ # unless the envelope carries Bitbucket's own `page` marker and no `next`,
1277
+ # which it reads back from `BB_LIST_NEXT_FILE` (`pr_list_states` sets the
1278
+ # path; this runs in that call's own subshell, so a global here would never
1279
+ # reach the caller). `page` is what tells a real paginated envelope from a
1280
+ # `values`-only shape that never carries `next` at all regardless of total —
1281
+ # the latter proves nothing and must fall through to the version table.
1165
1282
  #
1166
1283
  # THE HOST'S FAILURE TEXT AND EXIT CODE LEAVE UNTOUCHED, as in
1167
1284
  # `bb_branch_query`: `pr_list_call` classifies once, so a `429` still reads as
@@ -1177,6 +1294,7 @@ bb_state_listing() { # global bb args… --state <s> --json → one JSON array
1177
1294
  done
1178
1295
  [ -n "$_st" ] || die "bb_state_listing: no --state"
1179
1296
  _out="$(bb ${_args[@]+"${_args[@]}"} api "/repositories/{ws}/{repo}/pullrequests?state=$(bb_query_state "$_st")&pagelen=$BB_LIST_PAGELEN")" || return $?
1297
+ [ -n "${BB_LIST_NEXT_FILE:-}" ] && printf '%s' "$_out" | jq -r 'if (type=="object") and has("values") and has("page") then (if has("next") then "1" else "0" end) else "" end' > "$BB_LIST_NEXT_FILE"
1180
1298
  printf '%s' "$_out" | jq -c '.values // []'
1181
1299
  }
1182
1300
 
@@ -1262,15 +1380,19 @@ pr_sweep_report() { # $1=states answered $2=states asked
1262
1380
 
1263
1381
  pr_list_states() { # $1=backend $2=limit $3=states $4=jq-program; rest=the host command
1264
1382
  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=""
1383
+ local _s _raw _rc _err _tmp _ok=0 _failed=0 _first_rc=0 _failed_states="" BB_LIST_NEXT=""
1266
1384
  for _s in $states; do
1267
- plot_tmpfile _tmp "host-prlist-state-err-$_s" || return 3
1385
+ # `bb_state_listing` RUNS INSIDE THE SUBSTITUTION BELOW, its own subshell,
1386
+ # so a variable it sets cannot reach this one — the same trap `pr_list_call`
1387
+ # warns about for `die`. `BB_LIST_NEXT_FILE` is the channel out: a fresh,
1388
+ # already-empty temp path per state, read back once the substitution returns.
1389
+ plot_tmpfile _tmp "host-prlist-state-err-$_s" && plot_tmpfile BB_LIST_NEXT_FILE "host-prlist-next-$_s" || return 3
1268
1390
  # THE SUBSHELL'S CODE IS THE ONLY CHANNEL OUT, so it is captured rather
1269
1391
  # than propagated. `pr_list_failed` runs INSIDE the substitution and has
1270
1392
  # already composed its report and its repair line; that text is spooled
1271
1393
  # here only so the state's name can be added to it before it is passed on.
1272
1394
  _raw="$(pr_list_call "$@" --state "$_s" --json 2>"$_tmp")"; _rc=$?
1273
- _err="$(cat "$_tmp" 2>/dev/null)"; rm -f "$_tmp"
1395
+ 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
1396
  if [ "$_rc" -ne 0 ]; then
1275
1397
  # THE HOST'S OWN REPORT GOES FIRST AND IS NEVER PREFIXED. `pr_list_failed`
1276
1398
  # already composed the sentence that says WHY — a spent quota, a burst
@@ -1307,7 +1429,8 @@ pr_list_states() { # $1=backend $2=limit $3=states $4=jq-program; rest=the host
1307
1429
  # `PR_LIST_SINCE`; the GitHub arm carries its window as `--search`.
1308
1430
  [ -n "$PR_LIST_BRANCHES" ] || [ -n "$PR_LIST_SINCE" ] \
1309
1431
  || pr_list_report_truncation "$backend" "$limit" "$_s" \
1310
- "$(jq 'length' <<<"$_raw" 2>/dev/null || echo 0)"
1432
+ "$(jq 'length' <<<"$_raw" 2>/dev/null || echo 0)" "$BB_LIST_NEXT"
1433
+ [ -z "$PR_LIST_BIND_FN" ] || "$PR_LIST_BIND_FN" "$_raw"
1311
1434
  printf '%s' "$_raw" | jq -c ${PR_LIST_JQ_ARGS[@]+"${PR_LIST_JQ_ARGS[@]}"} "$jq_prog"
1312
1435
  done
1313
1436
  pr_sweep_report "$_ok" "$((_ok + _failed))"
@@ -1445,6 +1568,15 @@ ci_scheme() {
1445
1568
  # deliberately NOT `failed`, which claims the host did not answer.
1446
1569
  jenkins_build_map() {
1447
1570
  local instance="$1"
1571
+ # A Jenkins colour as a PR row's `checks` word, shared by both shapes of job.
1572
+ # Local, so the function lifts out of this file alone.
1573
+ local JEN_COLOUR_JQ='def color_to_checks:
1574
+ if . == null or . == "" then "none"
1575
+ elif endswith("_anime") then "pending"
1576
+ elif . == "blue" then "green"
1577
+ elif . == "red" or . == "yellow" then "failing"
1578
+ else "none"
1579
+ end; '
1448
1580
  local slug job
1449
1581
  slug="${instance%%/*}"
1450
1582
  if [ -n "${PLOT_JENKINS_JOB:-}" ]; then
@@ -1469,12 +1601,8 @@ jenkins_build_map() {
1469
1601
  # failure-shaped (cannot verify), never to ok — the probe's `classify` rule.
1470
1602
  local auth_out=""
1471
1603
  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
1604
+ printf '%s' "$auth_out" | grep -qiE 'jenkins auth:[[:space:]]*not reachable' && { printf '{"status":"failed","map":{}}\n'; return 0; }
1605
+ printf '%s' "$auth_out" | grep -qiE 'jenkins auth:[[:space:]]*(ok|reachable)' || { printf '{"status":"unknown","map":{}}\n'; return 0; }
1478
1606
 
1479
1607
  # THE SHAPE, READ FROM THE CONFIGURED JOB ITSELF. `job view` returns that
1480
1608
  # job's own `_class` — never a child's — plus the `color` and `lastBuild` a
@@ -1503,14 +1631,7 @@ jenkins_build_map() {
1503
1631
  # find it — `runs` reads that key, and the op's caller asks by the name the
1504
1632
  # instance declares.
1505
1633
  *'.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;
1634
+ printf '%s' "$view_out" | jq -c --arg job "$job" "$JEN_COLOUR_JQ"'
1514
1635
  ($job | split("/") | last) as $name
1515
1636
  | { status: "ok",
1516
1637
  map: { ($name): { color: .color,
@@ -1540,9 +1661,7 @@ jenkins_build_map() {
1540
1661
  # One call, every branch — the spike's whole point (Done-when 5).
1541
1662
  local out=""
1542
1663
  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
1664
+ [ -n "$out" ] && printf '%s' "$out" | jq -e 'type=="array"' >/dev/null 2>&1 || { printf '{"status":"failed","map":{}}\n'; return 0; }
1546
1665
 
1547
1666
  # Transform to `branch → {color, checks, job}`, decoding percent-encoded names
1548
1667
  # (Done-when 6: `feature%2Ffoo` → `feature/foo`, else every slashed branch
@@ -1557,17 +1676,10 @@ jenkins_build_map() {
1557
1676
  # red | yellow → failing (yellow is UNSTABLE — tests failed; NOT green)
1558
1677
  # *_anime → pending (a build is running)
1559
1678
  # disabled | absent → none (no build to report — absent is not failed)
1560
- printf '%s' "$out" | jq -c --arg job "$job" '
1679
+ printf '%s' "$out" | jq -c --arg job "$job" "$JEN_COLOUR_JQ"'
1561
1680
  def urldecode:
1562
1681
  gsub("%(?<h>[0-9A-Fa-f]{2})";
1563
1682
  "\(.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
1683
  # `job` NAMES the specific failing build for `failing_checks` — the whole
1572
1684
  # point of naming it is so a reader knows which Jenkins job to open. That is
1573
1685
  # the branch job, qualified by its container: `<container>/<branch>` (or the
@@ -1620,28 +1732,25 @@ jenkins_no_instance() {
1620
1732
  # estimate for. This draws it one step earlier, for a connector that does not
1621
1733
  # exist at all — and `resultOf` (`adapters/run-script.ts:211`) maps exit 4 onto
1622
1734
  # `unaskable`, which is the word the build port already answers with.
1623
- # The Jenkins REST credential, read from where `jen` already stores it.
1735
+ # The Jenkins REST credential: JENKINS_USER + JENKINS_API_TOKEN from the
1736
+ # environment, then `plot_env_file`, then the macOS keychain where `jen`
1737
+ # already stores it — the environment wins outright, same order and the same
1738
+ # both-or-neither rule as `jira_load_env_file`.
1624
1739
  #
1625
1740
  # 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*.
1741
+ # with an HTML login redirect — measured 2026-09-10. Jenkins' own API takes
1742
+ # BASIC auth with a user and an API token.
1743
+ #
1744
+ # Prints `user:token` and nothing else, or nothing at all — never the value
1745
+ # on a failure path. Empty means no source held a full pair; the caller turns
1746
+ # that into exit 4, *cannot be asked*.
1638
1747
  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
1748
+ local u="${JENKINS_USER:-}" t="${JENKINS_API_TOKEN:-}" src="the environment" found env_file
1749
+ [ -n "$u" ] || [ -n "$t" ] || { found="$(plot_env_file)"; [ -n "$found" ] && env_file="${found%|*}" && src="${found#*|}.env" && u="$(read_env_var JENKINS_USER "$env_file")" && t="$(read_env_var JENKINS_API_TOKEN "$env_file")"; }
1750
+ [ -n "$u" ] && [ -n "$t" ] && { echo "plot-host: JENKINS_USER and JENKINS_API_TOKEN read from $src" >&2; printf '%s:%s' "$u" "$t"; return 0; }
1751
+ 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
1752
  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"
1753
+ [ -n "$u" ] && [ -n "$t" ] || return 1; printf '%s:%s' "$u" "$t"
1645
1754
  }
1646
1755
 
1647
1756
  # A job path as Jenkins' REST API spells it: every segment under `job/`.
@@ -1655,18 +1764,30 @@ jenkins_job_url_path() { # $1 = job path, $2 = branch or ""
1655
1764
  local IFS=/
1656
1765
  for seg in $1; do [ -n "$seg" ] && out="$out/job/$seg"; done
1657
1766
  unset IFS
1658
- if [ -n "${2:-}" ]; then
1659
- out="$out/job/$(printf '%s' "$2" | sed 's|/|%2F|g')"
1660
- fi
1767
+ [ -n "${2:-}" ] && out="$out/job/$(printf '%s' "$2" | sed 's|/|%2F|g')"
1661
1768
  printf '%s' "$out"
1662
1769
  }
1663
1770
 
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
1771
+ # The REST host for the Jenkins slug $1, read off `jen -I <slug> auth status`'s
1772
+ # `Instance:` line rather than reinvented here — `jen` already turns a slug
1773
+ # like `ewz` into `jenkins-ci-ewz.internal.quatico.dev` and keys its stored
1774
+ # credential by that resolved host, so a literal slug sent to `curl` or to
1775
+ # `jenkins_rest_credential` can only fail. Prints nothing (exit 1) when `jen`
1776
+ # is missing, unparseable, or the line is absent — the caller decides what an
1777
+ # unresolved host means, same contract as every other helper here.
1778
+ jenkins_resolve_host() {
1779
+ local line; line=$(jen -I "$1" auth status 2>&1 | grep -iE '^Instance:' | head -1) || true
1780
+ [ -n "$line" ] && sed -nE 's/.*\(https?:\/\/([^)\/]+).*/\1/p' <<<"$line" || return 1
1781
+ }
1782
+
1783
+ # Every Jenkins build of one job, as a JSON array (newest first), or exit 3
1784
+ # (no instance) / exit 4 (cannot be asked). Shared by `run-for-sha`,
1785
+ # `runs-for-sha` and `runs`, so the instance, the credential and the
1667
1786
  # multibranch-then-plain URL fallback are written once.
1668
1787
  #
1669
- # $1 = the op's name, $2 = branch, $3 = how many builds to list, $4 = the sha.
1788
+ # $1 = the op's name, $2 = branch, $3 = how many builds to list, $4 = the sha
1789
+ # to filter for, or "" for every build of the branch unfiltered (the shape
1790
+ # `runs` wants — branch-scoped history, not one sha's).
1670
1791
  # Run it in `$(...)` and read the exit code with `|| exit $?`: it exits rather
1671
1792
  # than returns, and a subshell's exit is the code the caller sees.
1672
1793
  #
@@ -1678,55 +1799,161 @@ jenkins_job_url_path() { # $1 = job path, $2 = branch or ""
1678
1799
  # A BRANCH IS A JOB SEGMENT ON A MULTIBRANCH JOB AND NOT ON A PLAIN ONE, and no
1679
1800
  # reading of the configured path says which this is. The multibranch URL is
1680
1801
  # 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.
1802
+ # the plain job for a branch segment answers 404). THE PLAIN JOB REPORTS EVERY
1803
+ # BRANCH'S BUILDS, so an unfiltered read of it keeps only the builds whose
1804
+ # recorded `lastBuiltRevision.branch` names the asked branch, and a build that
1805
+ # records no branch only when the asked branch is the job's own key (the last
1806
+ # path segment, as `jenkins_build_map` keys it). A multibranch container that
1807
+ # answers `jobs` and no `builds` has not indexed the branch: an empty history.
1683
1808
  #
1684
1809
  # NO CREDENTIAL IS *CANNOT BE ASKED*, never *no run*: the keychain is macOS-only
1685
1810
  # and a Linux agent legitimately has none. AN UNREACHABLE INSTANCE IS NOT AN
1686
1811
  # EMPTY HISTORY: a refused or redirected request answers HTML, which fails the
1687
1812
  # `builds` test.
1688
1813
  #
1689
- # ONLY THE ASKED-FOR SHA, never another build's. `result` is null while a build
1814
+ # A BRANCH THE MULTIBRANCH JOB NEVER INDEXED IS AN EMPTY HISTORY, NOT A
1815
+ # REFUSAL. Measured live on ewz-kus-portal: `develop` builds in a separate job
1816
+ # (`kus-portal/continuous-deploy`), so the branch segment 404s and the
1817
+ # multibranch root answers only `{"_class":"…WorkflowMultiBranchProject"}` —
1818
+ # `tree=builds[…]` strips `jobs`, so a `has("jobs")` test never matches and the
1819
+ # function exited 4 for a Jenkins that had, in fact, answered. The decision is
1820
+ # keyed on the ROOT's `_class` rather than on `jobs`: widening `tree=` to carry
1821
+ # `jobs` would make a root that merely LISTS children (not this branch's
1822
+ # absence) answer `{"builds":[]}` too. An HTML body or no answer at all still
1823
+ # fails every test here and stays exit 4.
1824
+ #
1825
+ # THE DEFAULT BRANCH CAN NAME ITS OWN JOB, read through `Default branch job` —
1826
+ # the same key-reading shape `jenkins_instance` uses. It applies only when
1827
+ # `$branch` is the repository's local `origin/HEAD`, never to every branch:
1828
+ # ewz's other branches still build on the multibranch job, and a map nobody
1829
+ # has asked for is out of scope (brief: "a map is a surface nobody has asked
1830
+ # for"). `PLOT_JENKINS_JOB` still overrides `$job` for every branch, same
1831
+ # precedence as today — it wins, because it already means "ignore the
1832
+ # instance's own job path" and a narrower override must not un-set a broader
1833
+ # one.
1834
+ #
1835
+ # WITH A SHA, ONLY THAT SHA'S BUILDS, never another's. `result` is null while a build
1690
1836
  # runs, Jenkins' own word for *in flight*, mapped to the `status`/`conclusion`
1691
1837
  # split the contract already uses so the shape does not fork per connector.
1692
1838
  jenkins_sha_runs() {
1693
- local op="$1" branch="$2" limit="$3" sha="$4" instance host job cred tree body try path
1694
- instance="$(jenkins_instance)"
1695
- [ -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
1839
+ local op="$1" branch="$2" limit="$3" sha="$4" instance slug host job cred tree body try path plain="" default_job root_path
1840
+ instance="$(jenkins_instance)"; [ -n "$instance" ] || jenkins_no_instance
1841
+ slug="${instance%%/*}"; job="${instance#*/}"; [ "$job" = "$instance" ] && job=""
1842
+ default_job=$(bash "$here/plot-config.sh" get "Default branch job" "" 2>/dev/null || true); [ -n "$default_job" ] && [ "$branch" = "$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##')" ] && job="$default_job"
1843
+ [ -n "${PLOT_JENKINS_JOB:-}" ] && job="$PLOT_JENKINS_JOB"; [ -n "$job" ] || { echo "plot-host: $op — the Jenkins instance names no job path; a sha lives in a job's builds, so it must be <slug>/<job/path>, not a bare host" >&2; exit 4; }
1844
+ # A dotted slug IS a host already, `jen`'s own passthrough rule — only a
1845
+ # bare slug (`ewz`) needs resolving to the host its credential is keyed by.
1846
+ case "$slug" in *.*) host="$slug" ;; *) host="$(jenkins_resolve_host "$slug")" || { echo "plot-host: $op — cannot resolve Jenkins instance '$slug' to a host" >&2; echo " \`jen -I $slug auth status\` did not answer an 'Instance:' line; run it directly to see why." >&2; exit 4; } ;; esac
1704
1847
  cred="$(jenkins_rest_credential "$host")" || {
1705
1848
  echo "plot-host: $op — no Jenkins API credential for '$host'" >&2
1706
1849
  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
1850
  exit 4
1708
1851
  }
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
1852
+ tree="tree=builds%5Bnumber,result,building,timestamp,url,actions%5BlastBuiltRevision%5BSHA1,branch%5Bname%5D%5D%5D%5D%7B0,$limit%7D"
1853
+ body=""; root_path="$(jenkins_job_url_path "$job" "")"
1854
+ for path in "$(jenkins_job_url_path "$job" "$branch")" "$root_path"; do
1712
1855
  host_slot_take jenkins ''
1713
1856
  try=$(curl -sg --max-time 30 -u "$cred" "https://$host$path/api/json?$tree" 2>/dev/null) || true
1714
1857
  host_slot_give; budget_record_call jenkins ''
1715
1858
  if printf '%s' "$try" | jq -e 'has("builds")' >/dev/null 2>&1; then body="$try"; break; fi
1859
+ # ONLY AT THE ROOT: a multibranch container that answered its OWN `_class`
1860
+ # and no `builds` has not indexed this branch at all — an empty history,
1861
+ # not a refusal. Checking this on the BRANCH path too would be wrong: a
1862
+ # branch segment never carries a container's `_class`, so this arm would
1863
+ # never fire there anyway, but keying on "which path" rather than "which
1864
+ # body shape" keeps the empty-history reading from ever depending on what
1865
+ # a branch-level answer happens to contain.
1866
+ [ "$path" = "$root_path" ] && printf '%s' "$try" | jq -e '._class == "org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject"' >/dev/null 2>&1 && { body='{"builds":[]}'; break; }
1867
+ plain=1
1716
1868
  done
1717
1869
  cred=""
1718
1870
  if [ -z "$body" ]; then
1719
1871
  echo "plot-host: $op — Jenkins did not answer for '$host'" >&2
1720
1872
  exit 4
1721
1873
  fi
1722
- printf '%s' "$body" | jq -c --arg sha "$sha" '
1874
+ printf '%s' "$body" | jq -c --arg sha "$sha" --arg job "$job" --arg branch "$branch" --arg plain "$plain" 'def headsha($b): if (.br | length) > 0 then (first([.br, .shas] | transpose[] | select(.[0] == $b) | .[1]) // (.shas | last // "")) else (.shas | last // "") end;
1723
1875
  [ .builds[]
1724
- | { sha: ([ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision.SHA1 ] | first // ""),
1876
+ | { shas: [ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision.SHA1 ],
1877
+ br: [ .actions[]? | .lastBuiltRevision.branch[]?.name // empty | sub("^(refs/remotes/|refs/heads/)"; "") | sub("^origin/"; "") ],
1725
1878
  status: (if .building then "in_progress" else "completed" end),
1726
1879
  conclusion: (if .building then null else (.result // null) end),
1727
1880
  url: (.url // ""),
1728
- startedAt: (if .timestamp then (.timestamp / 1000 | todate) else "" end) } ]
1729
- | map(select(.sha == $sha))' || exit 4
1881
+ startedAt: (if .timestamp then (.timestamp / 1000 | todate) else "" end), workflow: $job } ] | map(select(.conclusion != "NOT_BUILT")) | (if $sha == "" then map(select(.conclusion != "ABORTED")) else . end)
1882
+ | if $sha != "" then map(select(headsha(if $plain == "" then $branch else ($job | split("/") | last) end) as $h | $h == $sha or (($sha | test("^[0-9a-f]{7,}$")) and ($h | startswith($sha))))) elif $plain == "" then .
1883
+ else map(select(if (.br | length) > 0 then any(.br[]; . == $branch) else $branch == ($job | split("/") | last) end)) end
1884
+ | map(.sha = (if $sha != "" then headsha(if $plain == "" then $branch else ($job | split("/") | last) end) else headsha($branch) end) | del(.shas, .br))' || exit 4
1885
+ }
1886
+
1887
+ # The sha-bound readings of the PR rows $3 whose branch colour in $2 cannot
1888
+ # settle the head: a JSON object keyed by branch, or nothing where no lookup
1889
+ # was needed. $1 = the op's name, $4 = optional path to also receive the
1890
+ # branches `rowsToBind` named this pass (one per line), so a caller can tell
1891
+ # "named but the ask broke early" (the colour must still stand, per "absent is
1892
+ # not false") from "never named because the row is past the cap" (the colour
1893
+ # must not stand) without a second, duplicate run of the same `rows` verb.
1894
+ # $5 = optional JSON object, branch -> the checksSha the caller's PR index
1895
+ # already has on record; a branch bound there to its CURRENT head costs the
1896
+ # pass nothing to re-confirm, so `rowsToBind` (rotation) spends the cap's
1897
+ # lookups on branches that are absent or stale there first. Absent entirely
1898
+ # where the caller holds no index — every row then sorts exactly as before.
1899
+ # `jenkins_sha_runs` reads each named row by sha, the bundle binds them. A
1900
+ # lookup that cannot ask Jenkins ends the pass, and the colour stands.
1901
+ jenkins_bind_rows() {
1902
+ local _named; _named="$({ jq -c . <<<"$2"; jq -c . <<<"$3"; jq -c . <<<"${5:-null}"; } | node "$here/board/plot-jenkins-pr-checks.mjs" rows 2>/dev/null)"
1903
+ : >"${4:-/dev/null}"; [ -z "$_named" ] && return; cut -f1 <<<"$_named" >"${4:-/dev/null}"
1904
+ printf '%s\n' "$_named" | while IFS=$'\t' read -r _b _s _j; do
1905
+ _r=$(jenkins_sha_runs "$1" "$_b" 20 "$_s" </dev/null) || break; printf '%s\t%s\t%s\t%s\n' "$_b" "$_s" "$_j" "$_r"
1906
+ done | node "$here/board/plot-jenkins-pr-checks.mjs" bind 2>/dev/null
1907
+ }
1908
+
1909
+ # Overlays the `mergeable` reading on a Bitbucket `pr-state`/`pr-list` row ($1,
1910
+ # carrying `state`, `headSha` and `base`) from a local `git merge-tree
1911
+ # --write-tree` check; Bitbucket Cloud's REST API has no conflict field (see
1912
+ # `bitbucket-pr-reading.ts`). The bundle folds the reading into an OPEN row and
1913
+ # returns every other row unchanged, so git runs for OPEN rows only.
1914
+ #
1915
+ # The base is fetched ALONE, once per distinct base per invocation
1916
+ # (`BB_FETCHED`), and a failed fetch reads `unknown`: a fetch that names the
1917
+ # head too fails whole on Bitbucket's short hash, and the stale `origin/<base>`
1918
+ # it leaves behind answers wrongly with confidence (#2208). The head is never
1919
+ # fetched; a head commit absent from the clone reads `unknown` with its sha.
1920
+ # `git fetch` is a git read, not a host CLI call, so the host stays unasked.
1921
+ # A bundle that cannot answer prints the unchanged row.
1922
+ bb_fold_mergeable() {
1923
+ local row="$1" state head base fetch="" in_clone="" mt_code="" mt_err=""
1924
+ IFS=$'\x1f' read -r state head base < <(jq -r '[.state, (.headSha // ""), (.base // "")] | join("\u001f")' <<<"$row" 2>/dev/null)
1925
+ if [ "$state" = OPEN ] && [ -n "$head" ] && [ -n "$base" ]; then
1926
+ case " ${BB_FETCHED:-} " in *" $base=ok "*) fetch=ok ;; *" $base=failed "*) fetch=failed ;; *) GIT_TERMINAL_PROMPT=0 git fetch -q origin "+refs/heads/$base:refs/remotes/origin/$base" 2>/dev/null && fetch=ok || fetch=failed; BB_FETCHED="${BB_FETCHED:-} $base=$fetch" ;; esac
1927
+ git cat-file -e "$head^{commit}" 2>/dev/null && in_clone=yes || in_clone=no
1928
+ [ "$fetch$in_clone" = okyes ] && { mt_err="$(git merge-tree --write-tree "origin/$base" "$head" 2>&1 >/dev/null)"; mt_code=$?; }
1929
+ fi
1930
+ printf '%s\n' "$row" "$head" "${base:+origin/$base}" "$(git --version 2>/dev/null)" "$fetch" "$in_clone" "$mt_code" "$mt_err" | node "$here/board/plot-bitbucket-mergeable.mjs" 2>/dev/null || printf '%s\n' "$row"
1931
+ }
1932
+
1933
+ # `pr-list --rich`'s per-line fold. Each row carries a `base` key only for
1934
+ # `bb_fold_mergeable`, and this removes it again; an OPEN row whose reading is
1935
+ # `unknown` gains `mergeableReason`. The loop runs in one shell, so
1936
+ # `BB_FETCHED` holds across its rows.
1937
+ bb_fold_mergeable_stream() { local line; while IFS= read -r line; do [ -z "$line" ] || bb_fold_mergeable "$line"; done | jq -c 'del(.base)'; }
1938
+
1939
+ # Prints the `pr-state` row of the Bitbucket PR payload $1 (`null` for no PR).
1940
+ #
1941
+ # Without `CI: jenkins` the check is `unknown`, absent and not false, as in
1942
+ # `pr-list`'s plain Bitbucket arm. Under it the branch colour from
1943
+ # `jenkins_build_map` settles `none` and `pending`, and a head whose colour is
1944
+ # `green` or `failing` is read by sha through `jenkins_bind_rows`, because a
1945
+ # colour carries no commit. Jenkins unreachable or no instance reads `unknown`.
1946
+ # `headSha` is `source.commit.hash`, a short hash `jenkins_sha_runs` prefix-matches.
1947
+ # `mergeable` is `unknown` here; `pr-state` folds the real reading on top with
1948
+ # `bb_fold_mergeable`, and `pr-merge --match-head` reads only `headSha`.
1949
+ bb_state_row() {
1950
+ local colours=null bound=null inst
1951
+ if jq -e '.id' >/dev/null 2>&1 <<<"$1" && [ "$(ci_scheme)" = "jenkins" ]; then
1952
+ inst="$(jenkins_instance)"
1953
+ [ -z "$inst" ] || colours="$(jenkins_build_map "$inst" | jq -c 'if .status == "ok" then (.map // {}) else null end' 2>/dev/null)" || colours=null
1954
+ [ "$colours" = null ] || bound="$(jenkins_bind_rows pr-state "$colours" "$(jq -c '[{headRefName:.source.branch.name,headRefOid:.source.commit.hash}]' <<<"$1")")"
1955
+ fi
1956
+ printf '%s\n%s\n%s\n' "$(jq -c . <<<"$1")" "$colours" "${bound:-null}" | node "$here/board/plot-jenkins-pr-checks.mjs" state
1730
1957
  }
1731
1958
 
1732
1959
  ci_unaskable() { # $1 = the op's name, $2 = the CI word (may be empty)
@@ -2058,14 +2285,14 @@ gh_rest_repo() {
2058
2285
  }
2059
2286
 
2060
2287
  rest_pr_to_state() {
2061
- jq -c '
2288
+ jq -c "$MERGEABLE_OF"'
2062
2289
  (if (.merged == true) or (.merged_at != null) then "MERGED"
2063
2290
  else (.state // "" | ascii_upcase) end) as $state
2064
2291
  | { number: .number,
2065
2292
  state: $state,
2066
2293
  draft: (.draft // false),
2067
2294
  url: (.html_url // ""),
2068
- mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown" }
2295
+ mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown", mergeable: mergeable_of }
2069
2296
  '
2070
2297
  }
2071
2298
 
@@ -2153,11 +2380,7 @@ bb_strip_ansi() {
2153
2380
  # means. Reads the already-stripped, already-lowercased error text.
2154
2381
  bb_issue_exit_code() {
2155
2382
  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
2383
+ 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
2384
  }
2162
2385
 
2163
2386
  # Assert the format the parse below was written against. `bb` puts its version
@@ -2174,13 +2397,20 @@ bb_issue_exit_code() {
2174
2397
  # that lists a `pr` command and no `issue` command is a bb that cannot be asked
2175
2398
  # about issues, which is exit 4 — the same answer as a disabled tracker. Any
2176
2399
  # other help text keeps the refusal below, exit 3. Exits 4 or 3; 0 passes.
2400
+ #
2401
+ # The `Tracker` advice below fits only where nobody declared one — asked of
2402
+ # the domain (`--bb-issue-missing`) rather than re-read here, since this is
2403
+ # the same declared value `issue_source` already read. A failed ask keeps
2404
+ # the advice: naming `Tracker` to a repository that declared one is
2405
+ # harmless, dropping it for one that has not would hide the fix.
2177
2406
  bb_assert_issue_version() {
2178
2407
  [ -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)"
2408
+ local v="$(bb --version 2>/dev/null | bb_strip_ansi | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)"
2181
2409
  if [ "$v" != "$BB_ISSUE_VERSION" ]; then
2182
2410
  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
2411
+ local missing="$(tracker_raw | node "$here/board/plot-issue-source.mjs" --bb-issue-missing 2>/dev/null)"
2412
+ [ -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"
2413
+ echo "plot-host: bb ${v:-unknown} $missing" >&2
2184
2414
  return 4
2185
2415
  fi
2186
2416
  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 +2535,7 @@ bb_test_json_support() {
2305
2535
  fi
2306
2536
 
2307
2537
  # 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
2538
+ grep -qiE 'not a bitbucket repo|repository not found' <<<"$out" && return 0
2311
2539
 
2312
2540
  # AN UNRECOGNISED FAILURE ACCEPTS, and this is a behaviour change the plan
2313
2541
  # argued for in round 1. Refusing on wording outside the three formats above
@@ -2499,16 +2727,10 @@ tracker_base_url() {
2499
2727
  # cannot express ABSENCE — an empty override falls through to the config — so
2500
2728
  # the absent case is tested with a repository that declares nothing.
2501
2729
  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
2730
  # One per line, trimmed, empties dropped. `plot-config.sh` already normalises
2509
2731
  # `A,B` to `A, B`, but an override arrives unnormalised and a hand-edited
2510
2732
  # 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
2733
+ 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
2734
  }
2513
2735
 
2514
2736
  # Reads ONE variable from a `.env`-shaped file. Evaluates nothing.
@@ -2538,6 +2760,25 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2538
2760
  -e 's/[[:space:]]*$//'
2539
2761
  }
2540
2762
 
2763
+ # The `.env` candidate for this checkout, and which of two locations it came
2764
+ # from. `.env` is untracked, so it lives only in the MAIN checkout — a fleet
2765
+ # desk or a scratch worktree under `Worktree root` has none of its own, and
2766
+ # `git rev-parse --show-toplevel` there answers with the WORKTREE, which never
2767
+ # holds one. Prints "<path>|" (worktree) or "<path>|the main checkout's" on a
2768
+ # readable candidate, or nothing when neither location has one.
2769
+ #
2770
+ # NO UPWARD WALK past either location — the fallback is exactly one more
2771
+ # place to look, not a search. `--git-common-dir`'s parent is the main
2772
+ # checkout root only for a standard `git worktree add` checkout; where the
2773
+ # command fails, prints nothing, or its parent directory does not exist, this
2774
+ # falls through to "no main checkout .env" rather than inventing a path.
2775
+ plot_env_file() {
2776
+ local root env_file common; root="$(git rev-parse --show-toplevel 2>/dev/null)" || root="."; env_file="$root/.env"
2777
+ [ -r "$env_file" ] && { printf '%s|' "$env_file"; return 0; }
2778
+ common="$(git rev-parse --git-common-dir 2>/dev/null)" && [ -n "$common" ] || return 0
2779
+ env_file="$(dirname "$common")/.env"; [ -r "$env_file" ] && printf "%s|the main checkout's " "$env_file"
2780
+ }
2781
+
2541
2782
  # The env var scheme for Jira auth. The plan left the EXACT names open, to be
2542
2783
  # confirmed against a real instance; these follow Jira Cloud's documented Basic
2543
2784
  # scheme (email + API token, base64'd into an Authorization header):
@@ -2551,48 +2792,24 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2551
2792
  # `die3` exits the whole script only from there, not from inside a command
2552
2793
  # substitution where it would end only the subshell and leak a second error.
2553
2794
  #
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.
2795
+ # WHERE BOTH ARE UNSET, `plot_env_file` IS READ, same order and both-or-neither
2796
+ # rule as `jenkins_rest_credential` — measured 2026-09-17, an operator holding
2797
+ # a working pair was sent to create a second token before this fallback
2798
+ # existed. THE VALUE IS NEVER PRINTED, only the source, so a 401 can be
2799
+ # debugged against the right one of two possible tokens.
2569
2800
  jira_load_env_file() {
2570
- local root env_file email token
2801
+ local found env_file source email token
2571
2802
  [ -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")"
2803
+ found="$(plot_env_file)"; [ -n "$found" ] || return 0; env_file="${found%|*}"; source="${found#*|}"
2804
+ email="$(read_env_var JIRA_EMAIL "$env_file")"; token="$(read_env_var JIRA_API_TOKEN "$env_file")"
2582
2805
  # BOTH OR NEITHER. Half a Basic credential authenticates nothing, and a
2583
2806
  # partial pickup would turn today's honest refusal into a 401 further in.
2584
2807
  [ -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
2808
+ export JIRA_EMAIL="$email" JIRA_API_TOKEN="$token"; echo "plot-host: JIRA_EMAIL and JIRA_API_TOKEN read from ${source}.env" >&2
2590
2809
  }
2591
2810
 
2592
2811
  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
2812
+ [ -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
2813
  jira_load_env_file
2597
2814
  if [ -z "${JIRA_EMAIL:-}" ] || [ -z "${JIRA_API_TOKEN:-}" ]; then
2598
2815
  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 +2894,14 @@ budget_record_jira() {
2677
2894
  # CAN be asked; if it cannot be reached, that is a failure to answer, not a host
2678
2895
  # that structurally has no tracker (the bitbucket-DISABLED case exit 4 is for).
2679
2896
  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
2897
+ local raw="$1" curl_rc="$2" status body detail
2898
+ [ "$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
2899
  # 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')"
2900
+ status="$(printf '%s' "$raw" | tail -n1)"; body="$(printf '%s' "$raw" | sed '$d')"
2689
2901
  if [ "$status" -lt 200 ] || [ "$status" -ge 300 ]; then
2690
2902
  # Name the status AND Jira's own errorMessages if it sent any (it returns
2691
2903
  # {"errorMessages":[…],"errors":{…}} on 4xx). 401/403 are the auth failures
2692
2904
  # this story exists to keep out of the inbox; 5xx is an outage. Both are 3.
2693
- local detail
2694
2905
  detail="$(printf '%s' "$body" | jq -r 'try (.errorMessages | join("; ")) catch empty' 2>/dev/null)"
2695
2906
  echo "plot-host: jira HTTP $status${detail:+ — $detail}" >&2
2696
2907
  return 3
@@ -2801,11 +3012,25 @@ bb_list_page_length() {
2801
3012
  # never see both for one state, and silence now means only that no claim was
2802
3013
  # owed — no `--limit`, or an empty page.
2803
3014
  #
3015
+ # THE ENVELOPE'S OWN `next` SUPERSEDES THE PAGE-LENGTH TEST, for any `bb`
3016
+ # version. #1757: `BB_LIST_PAGE_VERSIONS` names only versions this estate has
3017
+ # measured, so a page from any other version (1.11.1 included) could never be
3018
+ # proven complete by row count alone — 9 rows with no `next` read as "possibly
3019
+ # truncated" even though the envelope already answered. A page WITH `next`
3020
+ # proves nothing either way (Bitbucket could in principle set it with zero rows
3021
+ # left), so it falls through to the length test exactly as before. Absence,
3022
+ # never presence, is the signal — `$5` is "0" only when `bb_state_listing` read
3023
+ # an envelope with no `next` key; "1" means `next` was present; "" means no
3024
+ # envelope shape was read at all, and the version table alone decides, as
3025
+ # before this slice.
3026
+ #
2804
3027
  # $1 backend $2 requested limit (may be "") $3 state word $4 row count
3028
+ # $5 envelope's own completeness reading: "0" no next, "1" next present, ""
3029
+ # unknown (`BB_LIST_NEXT`, bitbucket only — github's listing carries none)
2805
3030
  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
3031
+ local be="$1" limit="$2" state="$3" count="$4" next="${5:-}" len=""
3032
+ # no --limit → no completeness claim owed; an empty page had nothing to hide
3033
+ [ -n "$limit" ] || return 0; [ "$count" -gt 0 ] 2>/dev/null || return 0
2809
3034
  if [ "$be" = "github" ]; then
2810
3035
  # github honours the limit: complete unless the page came back AT the limit.
2811
3036
  # Measured 2026-10-02 on this repository (1064 PRs): `--limit 1100`
@@ -2814,9 +3039,10 @@ pr_list_report_truncation() {
2814
3039
  # exist rather than the rows requested.
2815
3040
  if [ "$count" -lt "$limit" ] 2>/dev/null; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
2816
3041
  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
3042
+ # A fixed page: complete below a measured length, or whose own envelope
3043
+ # named no further page — unprovable otherwise.
3044
+ [ "$next" = "0" ] || len="$(bb_list_page_length)"
3045
+ if [ "$next" = "0" ] || { [ -n "$len" ] && [ "$count" -lt "$len" ] 2>/dev/null; }; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
2820
3046
  fi
2821
3047
  # Named per state so a caller can resolve exactly the states that were
2822
3048
  # capped, not a whole-call flag that over-reports.
@@ -3133,8 +3359,7 @@ budget_record_call() { # $1=connector $2=backend-for-account $3=bucket
3133
3359
  [ -z "${PLOT_BUDGET_OFF:-}" ] || return 0
3134
3360
  local reading account bucket
3135
3361
  account="$(budget_account "${2:-$1}")"
3136
- bucket="${3:-}"
3137
- [ -n "$bucket" ] || bucket="$(budget_bucket "$1")"
3362
+ bucket="${3:-}"; [ -n "$bucket" ] || bucket="$(budget_bucket "$1")"
3138
3363
  # A HARVESTED HEADER OUTRANKS EVERYTHING, including the argv's guess at the
3139
3364
  # bucket: `X-RateLimit-Resource` names `code_search` for a search that no
3140
3365
  # reading of the command line would have classified as anything but `core`.
@@ -3420,9 +3645,7 @@ be="$(backend)" || exit $?
3420
3645
  # `gh_route`, never reads a budget, and `$route` stays empty for it. That
3421
3646
  # emptiness is the honest value — there is no route where there is no fork.
3422
3647
  route=""
3423
- if [ "$be" = "github" ]; then
3424
- route="$(gh_route "$op")"
3425
- fi
3648
+ [ "$be" = "github" ] && route="$(gh_route "$op")"
3426
3649
 
3427
3650
  case "$op" in
3428
3651
  backend)
@@ -3560,9 +3783,9 @@ case "$op" in
3560
3783
  # mergeCommit is what lets a caller ask "which release contains this?" —
3561
3784
  # `git tag --contains <sha>` answers exactly, where dates cannot. It is ""
3562
3785
  # 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
3786
+ elif out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json number,state,isDraft,url,mergeCommit,headRefOid,baseRefName,statusCheckRollup,mergeable,mergeStateStatus 2>"$HOST_ERR")"; then
3564
3787
  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"
3788
+ jq -c "$CHECKS_OF$MERGEABLE_OF"'{number:.number,state:.state,draft:.isDraft,url:.url,mergeCommit:(.mergeCommit.oid // ""),headSha:(.headRefOid // ""),base:(.baseRefName // ""),checks:checks_of,checksSha:(.headRefOid // ""),mergeable:mergeable_of}' <<<"$out"
3566
3789
  else
3567
3790
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3568
3791
  # REFUSED FOR RATE IS NOT ANSWERED. The budget gate above could not see
@@ -3599,7 +3822,7 @@ case "$op" in
3599
3822
  if [[ "$ref" =~ ^[0-9]+$ ]]; then
3600
3823
  if out="$(bb ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json 2>"$HOST_ERR")"; then
3601
3824
  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"
3825
+ bb_fold_mergeable "$(bb_state_row "$out")"
3603
3826
  else
3604
3827
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3605
3828
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
@@ -3623,16 +3846,25 @@ case "$op" in
3623
3846
  #
3624
3847
  # A declined-only or PR-less branch still pays for all three; those are
3625
3848
  # the cases where the third call is the one carrying the answer.
3849
+ #
3850
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER. `bb_branch_query`
3851
+ # replaces each state's whole-repository page with the per-branch REST
3852
+ # filter, costing one request per state asked instead of one page that
3853
+ # cannot see past its first 50 rows — `pr-merged`'s header has the
3854
+ # measurement. `bb_states_for all` still expands to three calls because
3855
+ # `bb pr list` (and this REST filter) has no `all` state.
3856
+ #
3857
+ # NO "FULL PAGE, NO MATCH" GUARD HERE, unlike the single-state arms
3858
+ # below. The loop breaks on the first non-empty page, and every row in
3859
+ # it already matches `$ref` — `bb_branch_query` filtered server-side —
3860
+ # so a full page is 50 real answers, never a truncated non-match. The
3861
+ # condition the other arms guard against cannot occur in this walk.
3626
3862
  out=""; bb_rc=0
3627
3863
  bb_all_states="$(bb_states_for all)" || exit 1
3628
3864
  for _s in $bb_all_states; do
3629
- if _part="$(bb ${repo_args[@]+"${repo_args[@]}"} pr list --state "$_s" --json 2>"$HOST_ERR")"; then
3865
+ if _part="$(bb_branch_query "$ref" "$_s" ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3630
3866
  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
3867
+ [ "$(jq 'length' <<<"$_part")" -gt 0 ] && break
3636
3868
  else
3637
3869
  bb_rc=1; break
3638
3870
  fi
@@ -3646,11 +3878,10 @@ case "$op" in
3646
3878
  # from the answer. A fix touching only the numeric pair above would
3647
3879
  # leave that caller reading an absent key on every Bitbucket repo.
3648
3880
  #
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"
3881
+ # The hash rides on the page the branch query already fetched, so this
3882
+ # costs no extra call. `bb_branch_query` already filtered to the
3883
+ # branch, so every row in `out` already matches it.
3884
+ bb_fold_mergeable "$(bb_state_row "$(jq -c '.[0] // null' <<<"$out")")"
3654
3885
  else
3655
3886
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3656
3887
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
@@ -3681,57 +3912,47 @@ case "$op" in
3681
3912
  esac
3682
3913
  done
3683
3914
  # 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"
3915
+ if [ ${#repo_args[@]} -eq 0 ] && [ -z "$(git remote 2>/dev/null)" ]; then echo "not-merged"; else
3916
+ if [ "$be" = "github" ]; then
3917
+ # --state all, because a merged PR reports CLOSED and the default `open`
3918
+ # would hide every one of them. --limit 100 rather than 1: the newest PR
3919
+ # is not the merge, exactly as the state is not the merge.
3920
+ if out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit 100 --json mergedAt 2>"$HOST_ERR")"; then
3921
+ rm -f "$HOST_ERR"
3922
+ jq -e 'any(.[]; .mergedAt != null)' >/dev/null 2>&1 <<<"$out" && echo "merged" || echo "not-merged"
3719
3923
  else
3720
- echo "not-merged"
3924
+ err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3925
+ miss_or_unknown "$err"
3721
3926
  fi
3722
3927
  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"
3928
+ bb_require_json
3929
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER. `bb pr list --state
3930
+ # merged` returns one fixed page of 50, newest first, and a branch whose
3931
+ # merge is older than that page reads as unmerged — measured 2026-10-20
3932
+ # on ewz-kus-portal: PR #3644 merged 2026-09-26, invisible to a page that
3933
+ # reached back only to 2026-09-30. `bb_branch_query` puts
3934
+ # `source.branch.name` inside `q=` so the host filters, costing one
3935
+ # request instead of a listing this adapter refuses to page past its
3936
+ # ceiling (see `bb_branch_sweep`'s header).
3937
+ if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3938
+ rm -f "$HOST_ERR"
3939
+ # A FULL PAGE CANNOT PROVE ABSENCE. `bb_branch_query` asks pagelen=50,
3940
+ # and a branch carrying more than 50 merged PRs could hide a MERGED row
3941
+ # past it — so 50 rows with none matching answers `unknown`, not
3942
+ # `not-merged`, the same rule a failed call follows below.
3943
+ if jq -e 'any(.[]; .state == "MERGED")' >/dev/null 2>&1 <<<"$out"; then echo "merged"
3944
+ elif bb_full_page_lacks "$out" 'any(.[]; .state == "MERGED")'; then echo "plot-host: pr-merged: the branch query for '$ref' returned a full page with no merged PR; cannot prove absence" >&2; echo "unknown"
3945
+ else echo "not-merged"
3946
+ fi
3726
3947
  else
3727
- echo "plot-host: $err" >&2
3728
- echo "unknown"
3948
+ err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3949
+ miss_or_unknown "$err"
3729
3950
  fi
3730
3951
  fi
3731
3952
  fi
3732
3953
  ;;
3733
3954
 
3734
- pr-merge-commit)
3955
+ pr-merge-commit|pr-merge-dest)
3735
3956
  # THE MERGE COMMIT OF A BRANCH'S MERGED PR, and nothing else.
3736
3957
  #
3737
3958
  # A SECOND SUBCOMMAND RATHER THAN A FIELD ON `pr-merged`, because that one
@@ -3751,22 +3972,29 @@ case "$op" in
3751
3972
  #
3752
3973
  # PRINTS NOTHING AND EXITS 0 where no PR merged — an ANSWER, the same shape
3753
3974
  # `pr-state` gives for a missing PR. Exit 3 is the question failing.
3754
- ref="${1:?pr-merge-commit needs a branch}"; shift || true
3975
+ #
3976
+ # `pr-merge-dest` RUNS THE SAME QUERY and prints every merged PR instead of
3977
+ # the first sha: one `number<TAB>base<TAB>sha<TAB>mergedAt` line each, read
3978
+ # off the same payload. `plot-release-chain.mjs` asks it once per hop of a
3979
+ # release-chain walk. Bitbucket names no merge time, so `mergedAt` is
3980
+ # `updated_on`, as in `pr-list`.
3981
+ ref="${1:?$op needs a branch}"; shift || true
3755
3982
  repo_args=()
3756
3983
  while [ $# -gt 0 ]; do
3757
3984
  case "$1" in
3758
3985
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
3759
- *) die "pr-merge-commit: unknown arg $1" ;;
3986
+ *) die "$op: unknown arg $1" ;;
3760
3987
  esac
3761
3988
  done
3989
+ if [ "$op" = pr-merge-dest ]; then pick='.[] | [.n, .b, .s, .t] | @tsv'; else pick='first.s // empty'; fi
3762
3990
  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
3991
+ if out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit 100 --json number,mergedAt,mergeCommit,baseRefName 2>"$HOST_ERR")"; then
3764
3992
  rm -f "$HOST_ERR"
3765
3993
  # The FIRST merged PR carrying a sha. A branch may hold several merged
3766
3994
  # PRs; each names its own merge commit, and any of them is a commit that
3767
3995
  # landed this branch's work.
3768
- jq -r 'map(select(.mergedAt != null and .mergeCommit != null))
3769
- | map(.mergeCommit.oid) | first // empty' <<<"$out"
3996
+ jq -r 'map(select(.mergedAt != null and .mergeCommit != null)
3997
+ | {n: .number, b: (.baseRefName // ""), s: .mergeCommit.oid, t: .mergedAt}) | '"$pick" <<<"$out"
3770
3998
  else
3771
3999
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3772
4000
  # A lookup miss is an answer: no PR, so no merge commit. Anything else
@@ -3776,11 +4004,14 @@ case "$op" in
3776
4004
  fi
3777
4005
  else
3778
4006
  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
4007
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER — `pr-merged`'s header
4008
+ # states the measurement and the cost. Bitbucket names the merge commit
4009
+ # `merge_commit.hash` on a merged PR.
4010
+ if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3781
4011
  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"
4012
+ bb_full_page_lacks "$out" 'any(.[]; .merge_commit.hash != null)' && { echo "plot-host: $op: the branch query for '$ref' returned a full page with no merge commit; cannot prove absence" >&2; exit 3; }
4013
+ jq -r 'map(select(.merge_commit.hash != null)
4014
+ | {n: .id, b: (.destination.branch.name // ""), s: .merge_commit.hash, t: (.updated_on // "")}) | '"$pick" <<<"$out"
3784
4015
  else
3785
4016
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3786
4017
  miss_or_exit3 "$err"
@@ -3813,33 +4044,33 @@ case "$op" in
3813
4044
  jq -r '.[] | select(.mergedAt != null and .headRefOid != null) | .headRefOid' <<<"$out" || exit 3
3814
4045
  else
3815
4046
  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
4047
+ [ -n "$err" ] && is_lookup_miss "$err" || { echo "plot-host: ${err:-gh pr list failed}" >&2; exit 3; }
3822
4048
  fi
3823
4049
  else
3824
4050
  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
4051
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER — `pr-merged`'s header
4052
+ # states the measurement and the cost. Bitbucket names the merged head
4053
+ # `source.commit.hash`.
4054
+ if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3827
4055
  rm -f "$HOST_ERR"
3828
- jq -r --arg b "$ref" '.[] | select(.source.branch.name==$b) | (.source.commit.hash // empty)' <<<"$out" || exit 3
4056
+ bb_full_page_lacks "$out" 'any(.[]; .source.commit.hash != null)' && { echo "plot-host: pr-merged-heads: the branch query for '$ref' returned a full page with no merged head; cannot prove absence" >&2; exit 3; }
4057
+ jq -r '.[] | (.source.commit.hash // empty)' <<<"$out" || exit 3
3829
4058
  else
3830
4059
  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
4060
+ [ -n "$err" ] && is_lookup_miss "$err" || { echo "plot-host: ${err:-the branch query failed}" >&2; exit 3; }
3837
4061
  fi
3838
4062
  fi
3839
4063
  ;;
3840
4064
 
3841
4065
  pr-review)
3842
- [ "$be" = "github" ] || { echo "plot-host: pr-review: bitbucket is not supported yet" >&2; exit 4; }
4066
+ if [ "$be" != "github" ]; then
4067
+ pr="/repositories/{ws}/{repo}/pullrequests/${1:?pr-review needs a PR number}"
4068
+ out="$(bb api "$pr")" && sha="$(jq -re '.source.commit.hash' <<<"$out")" \
4069
+ && st="$(bb api "/repositories/{ws}/{repo}/commit/$sha/statuses?sort=-created_on&pagelen=50")" && cm="$(bb api "$pr/comments?pagelen=100")" \
4070
+ && printf '%s\n%s\n%s\n' "$sha" "$(jq -c . <<<"$st")" "$(jq -c . <<<"$cm")" | node "$here/board/plot-jenkins-pr-checks.mjs" review \
4071
+ || { echo "plot-host: pr-review: the read failed" >&2; exit 3; }
4072
+ exit 0
4073
+ fi
3843
4074
  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
4075
  && 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
4076
  || { echo "plot-host: pr-review: the read failed" >&2; exit 3; } ;;
@@ -3857,19 +4088,11 @@ case "$op" in
3857
4088
  esac
3858
4089
  done
3859
4090
  [ -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
4091
+ args=(pr create --title "$title" --body "$body")
4092
+ [ -n "$base" ] && args+=(--base "$base")
4093
+ [ -n "$head" ] && args+=(--head "$head")
4094
+ [ "$draft" = 1 ] && args+=(--draft)
4095
+ if [ "$be" = "github" ]; then gh "${args[@]}"; else bb "${args[@]}"; fi
3873
4096
  ;;
3874
4097
 
3875
4098
  pr-merge)
@@ -3892,16 +4115,17 @@ case "$op" in
3892
4115
  # answers 5 with its one-line notice where no key is declared: the merge
3893
4116
  # then runs as the signed-in `gh` identity. The token goes straight into
3894
4117
  # GH_TOKEN — never into argv, a file, or a log line.
3895
- merger_repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null)
4118
+ merger_repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null) || { echo "plot-host: pr-merge: gh repo view could not resolve owner/repo from the current checkout" >&2; exit 3; }
3896
4119
  merger_token=$(node "$here/plot-merger-token.mjs" "$merger_repo") || { mc=$?; [ "$mc" = 5 ] || exit "$mc"; }
3897
4120
  args=(pr merge "$num"); [ "$squash" = 1 ] && args+=(--squash) || args+=(--merge); [ "$delbranch" = 1 ] && args+=(--delete-branch)
3898
4121
  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
4122
+ # Bitbucket's merge endpoint takes no head precondition (measured 2026-10-18,
4123
+ # see plan Notes), so the pin is enforced by re-reading the head via bb_state_row
4124
+ # right before merging; it matches by prefix, 7+ hex (domain's sameCommit).
4125
+ elif [ -n "$pin" ]; then bb_require_json; head_out="$(bb pr view "$num" --json 2>"$HOST_ERR")" || { err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"; echo "plot-host: $err" >&2; exit 3; }; rm -f "$HOST_ERR"; head_sha="$(bb_state_row "$head_out" | jq -r '.headSha // ""')"; head_l="$(printf '%s' "$head_sha" | tr '[:upper:]' '[:lower:]')"; pin_l="$(printf '%s' "$pin" | tr '[:upper:]' '[:lower:]')"; [[ "$head_l" =~ ^[0-9a-f]{7,}$ && "$pin_l" =~ ^[0-9a-f]{7,}$ ]] && { [[ "$head_l" == "$pin_l"* ]] || [[ "$pin_l" == "$head_l"* ]]; } || { echo "plot-host: pr-merge --match-head: head-moved — PR #$num is at ${head_sha:-unknown}, caller read $pin; nothing was merged" >&2; exit 1; }; args=(pr merge "$num"); [ "$squash" = 1 ] && args+=(--squash); [ "$delbranch" = 1 ] && args+=(--delete-branch); bb "${args[@]}"
3900
4126
  else
3901
- args=(pr merge "$num")
3902
- [ "$squash" = 1 ] && args+=(--squash)
3903
- [ "$delbranch" = 1 ] && args+=(--delete-branch)
3904
- bb "${args[@]}"
4127
+ echo "plot-host: pr-merge: bitbucket needs --match-head <sha>; nothing was merged" >&2
4128
+ exit 1
3905
4129
  fi
3906
4130
  ;;
3907
4131
 
@@ -3942,13 +4166,12 @@ case "$op" in
3942
4166
  # --state all, where the newest 30 crowd out every older merged PR. A caller
3943
4167
  # that wants history says how much; the default stays the host's, so no
3944
4168
  # existing caller's result changes.
3945
- limit=""
3946
- branches=""
4169
+ limit=""; branches=""
3947
4170
  # THE WINDOW, AND IT IS THE HOST'S OWN STAMP. Empty means ask about
3948
4171
  # everything, which is what every caller predating this asks and what a
3949
4172
  # caller with no stored watermark must ask. A caller that has one sends it
3950
4173
  # verbatim — see the header: re-rendering it is how a window closes forever.
3951
- since=""
4174
+ since=""; _bound_shas=""
3952
4175
  while [ $# -gt 0 ]; do
3953
4176
  case "$1" in
3954
4177
  --state) state="${2:?}"; shift 2 ;;
@@ -3991,6 +4214,14 @@ case "$op" in
3991
4214
  # over the wrong set answers confidently about branches nobody asked
3992
4215
  # about while missing the ones they did.
3993
4216
  --branch) branches="${branches:+$branches }${2:?}"; shift 2 ;;
4217
+ # ROTATION'S READ-ONLY INPUT (`bitbucket-jenkins-a-pr-list-row`):
4218
+ # branch -> the `checksSha` the caller's PR index already has on
4219
+ # record, JSON, so `jenkins_bind_rows` spends this pass's capped
4220
+ # lookups on branches the index does NOT yet confirm bound to their
4221
+ # current head. OPT-IN, like `--branch` above — a caller with no
4222
+ # index (or none built yet) passes nothing, and every row sorts
4223
+ # exactly as it always has.
4224
+ --bound-shas) _bound_shas="${2:?}"; shift 2 ;;
3994
4225
  *) die "pr-list: unknown arg $1" ;;
3995
4226
  esac
3996
4227
  done
@@ -4034,8 +4265,7 @@ case "$op" in
4034
4265
  jen_map=""
4035
4266
  jen_status=""
4036
4267
  if [ "$ci" = "jenkins" ] && [ "$rich" = 1 ]; then
4037
- jen_instance="$(jenkins_instance)"
4038
- [ -n "$jen_instance" ] || jenkins_no_instance
4268
+ jen_instance="$(jenkins_instance)"; [ -n "$jen_instance" ] || jenkins_no_instance
4039
4269
  jen_payload=$(jenkins_build_map "$jen_instance")
4040
4270
  jen_status=$(printf '%s' "$jen_payload" | jq -r '.status // "failed"' 2>/dev/null || echo "failed")
4041
4271
  jen_map=$(printf '%s' "$jen_payload" | jq -c '.map // {}' 2>/dev/null || echo "{}")
@@ -4167,10 +4397,12 @@ case "$op" in
4167
4397
  # a GitHub repo without Jenkins still reads its own rollup exactly as
4168
4398
  # before.
4169
4399
  # 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.
4400
+ # arms. `checksSha` is emitted by the rollup arm (`statusCheckRollup`
4401
+ # belongs to the head commit, so it equals `headSha`) and by the
4402
+ # Jenkins arm wherever a sha-bound Jenkins read (`board/plot-jenkins-pr-checks.mjs`)
4403
+ # found a build for that exact head — never from the branch-colour map,
4404
+ # which carries no commit. The plain arm reads no checks and emits none.
4405
+ # `mergedAt` is the host's, `""` on an open PR.
4174
4406
  if [ "$ci" = "jenkins" ]; then
4175
4407
  # GitHub PR list, but `checks` comes from Jenkins, joined on branch
4176
4408
  # name. `statusCheckRollup` is NOT even requested — the GitHub rollup
@@ -4183,31 +4415,45 @@ case "$op" in
4183
4415
  --json number,title,state,headRefName,isDraft,mergeable,mergeStateStatus,reviewDecision,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4184
4416
  pr_list_report_truncation github "$limit" "$state" \
4185
4417
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
4418
+ # GAPS 3/4/10: `jmap` names no commit, so a push between builds would
4419
+ # carry the OLD head's colour onto the new one. The bundle names the
4420
+ # rows `jmap` cannot settle (green/failing with a head sha, at most
4421
+ # `SHA_LOOKUPS_PER_PASS`); this reads each one's builds by sha, and the
4422
+ # bundle binds them. A lookup that exits non-zero could not ask: no row
4423
+ # gets a reading from it, the pass asks no further row.
4424
+ # 20 builds per lookup: one round trip at any window, and a plain job lists every branch's builds.
4425
+ #
4426
+ # A ROW PAST THE CAP IS NOT THE SAME AS A ROW A BROKEN ASK LEAVES
4427
+ # UNBOUND. `none`/`pending` need no commit, so `$jmap` answers them
4428
+ # safely either way. For `green`/`failing`: a row `$named` lists but
4429
+ # `$shamap` has no entry for is one `jenkins_sha_runs` never reached
4430
+ # because an earlier ask in the same pass broke — "a lookup that
4431
+ # cannot ask is not an answer", carried over unchanged from #2053/
4432
+ # #2075, so its colour stands. A row `$named` never listed is past
4433
+ # `SHA_LOOKUPS_PER_PASS` (`rowsToBind`) and reads `unknown`: its
4434
+ # colour may belong to a commit this PR no longer carries (same gap
4435
+ # as the Bitbucket arm, `bitbucket-jenkins-pr-list-rows-past`).
4436
+ 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
4437
  printf '%s' "$_gh_raw" \
4187
- | jq -c --argjson jmap "$jen_map" --arg jstatus "$jen_status" '.[] |
4188
- ($jmap[.headRefName] // null) as $jentry |
4438
+ | jq -c --argjson jmap "$jen_map" --argjson shamap "${_sha_map:-null}" --argjson named "${_named:-[]}" --arg jstatus "$jen_status" "$MERGEABLE_OF"'.[] |
4439
+ ($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 |
4440
+ # A ROW `$eff == null` WITH `$ambiguous` NEVER GOT A JENKINS ANSWER
4441
+ # THIS PASS — past the cap, or a lookup that broke early. That is a
4442
+ # different fact from Jenkins NAMING "unknown", so it carries its
4443
+ # own field rather than collapsing into the same `checks` word
4444
+ # (`bitbucket-jenkins-a-pr-list-row`).
4189
4445
  {
4190
4446
  number:.number, title:.title, state:.state, head:.headRefName,
4191
4447
  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),
4448
+ checks:(if $jstatus != "ok" then "unknown" elif $eff == null then (if $ambiguous then "unknown" else "none" end) else $eff.checks end),
4449
+ mergeable:mergeable_of,
4201
4450
  review:(.reviewDecision // ""),
4202
4451
  url:.url,
4203
4452
  updatedAt:(.updatedAt // ""),headSha:(.headRefOid // ""),mergedAt:(.mergedAt // ""),
4453
+ checksSha:($eff.checksSha // ""),
4204
4454
  author:(.author.login // ""),
4205
- failing_checks:(
4206
- if $jentry != null and $jentry.checks == "failing"
4207
- then [$jentry.job]
4208
- else []
4209
- end)
4210
- }'
4455
+ failing_checks:(if $eff.checks == "failing" then [$eff.job] else [] end)
4456
+ } + (if $jstatus == "ok" and $ambiguous and $eff == null then {checksLookup:"skipped"} else {} end)'
4211
4457
  else
4212
4458
  # GitHub without Jenkins (or Jenkins not configured): use GitHub rollup
4213
4459
  _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} \
@@ -4215,14 +4461,11 @@ case "$op" in
4215
4461
  pr_list_report_truncation github "$limit" "$state" \
4216
4462
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
4217
4463
  printf '%s' "$_gh_raw" \
4218
- | jq -c "$CHECKS_OF"'.[] | {
4464
+ | jq -c "$CHECKS_OF$MERGEABLE_OF"'.[] | {
4219
4465
  number:.number, title:.title, state:.state, head:.headRefName,
4220
4466
  draft:.isDraft,
4221
4467
  checks:checks_of,
4222
- mergeable:(
4223
- if .mergeable=="CONFLICTING" or .mergeStateStatus=="DIRTY" then "conflicting"
4224
- elif .mergeable=="MERGEABLE" then "mergeable"
4225
- else "unknown" end),
4468
+ mergeable:mergeable_of,
4226
4469
  review:(.reviewDecision // ""),
4227
4470
  url:.url,
4228
4471
  updatedAt:(.updatedAt // ""),headSha:(.headRefOid // ""),checksSha:(.headRefOid // ""),mergedAt:(.mergedAt // ""),
@@ -4283,9 +4526,7 @@ case "$op" in
4283
4526
  # listing; a per-branch query returns that branch's pull requests and
4284
4527
  # nothing was capped, so the notice would describe a truncation that did
4285
4528
  # 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
4529
+ [ -n "$limit" ] && [ -z "$branches" ] && [ -z "$since" ] && echo "plot-host: bitbucket ignores --limit $limit; the listing returns one page of 50 per state" >&2
4289
4530
  # Establish that bb supports --json BEFORE calling it — Done-when 5.
4290
4531
  bb_require_json
4291
4532
  # Resolve the states BEFORE the loop. `for s in $(bb_states_for …)` runs
@@ -4313,7 +4554,6 @@ case "$op" in
4313
4554
  # caller that asked for a window and got a full listing must not read the
4314
4555
  # answer as a delta.
4315
4556
  PR_LIST_SINCE="$since"
4316
- PR_SWEEP_ASKED=0
4317
4557
  # THE PLAIN LISTING IS `bb_state_listing`, one request per state at
4318
4558
  # `pagelen=50`, where `bb pr list` walks 10-row pages. Its header has the
4319
4559
  # measurement.
@@ -4333,9 +4573,42 @@ case "$op" in
4333
4573
  # Bitbucket PR list, `checks` filled from Jenkins — the SAME overlay
4334
4574
  # the GitHub arm uses, which is why it lives above the backend branch.
4335
4575
  # `bb`'s standing `unknown` becomes a real value where Jenkins answers.
4336
- PR_LIST_JQ_ARGS=(--argjson jmap "$jen_map" --arg jstatus "$jen_status")
4576
+ #
4577
+ # A PUSH BETWEEN BUILDS LEAVES `$jmap`'S COLOUR STALE, same gap the
4578
+ # GitHub arm closed (#1959/#1974): the branch-colour map carries no
4579
+ # commit, so a green row can describe a head Jenkins never built. The
4580
+ # fix is `jenkins_bind_rows` (`pr-state`'s own bind path, #1974),
4581
+ # called here via `PR_LIST_BIND_FN` because `pr_list_states` loops
4582
+ # per Bitbucket state and each state's rows are the only place the
4583
+ # head shas live — see that global's header.
4584
+ #
4585
+ # A ROW `jenkins_bind_rows` DROPPED FOR THE CAP (`SHA_LOOKUPS_PER_PASS`,
4586
+ # `rowsToBind`) IS NOT THE SAME AS A ROW IT NEVER NEEDED TO ASK ABOUT.
4587
+ # `$jmap`'s colour binds safely for `none`/`pending` — neither needs a
4588
+ # commit — but `green`/`failing` carry the PREVIOUS head's result, the
4589
+ # defect `rowsToBind` exists to flag by leaving the row out of
4590
+ # `$shamap`.
4591
+ #
4592
+ # AND A ROW PAST THE CAP IS NOT THE SAME AS ONE THE CAP NAMED WHOSE
4593
+ # ASK THEN BROKE EARLY. `$named` (`jenkins_bind_rows`'s own 4th-arg
4594
+ # side file, pure and network-free) lists exactly what `rowsToBind`
4595
+ # selected. A row `$named` never lists is past the cap and reads
4596
+ # `unknown`: its colour may belong to a commit this PR no longer
4597
+ # carries. A row `$named` lists but `$shamap` has no entry for is one
4598
+ # `jenkins_sha_runs` never reached because an earlier ask in the same
4599
+ # pass broke early — "a lookup that cannot ask is not an answer",
4600
+ # carried over unchanged from #2053/#2075, so its colour stands.
4601
+ # `updatedAt` travels too: `rowsToBind` sorts by it to pick the most
4602
+ # recently updated rows, and a row list that never carries it sorts
4603
+ # as a no-op, leaving the cap keyed on array order instead.
4604
+ _bb_jen_bind() { local s n named_file; plot_tmpfile named_file host-bbprlist-named; s="$(jenkins_bind_rows pr-list "$jen_map" "$(jq -c '[.[] | {headRefName:.source.branch.name,headRefOid:.source.commit.hash,updatedAt:.updated_on}]' <<<"$1")" "$named_file" "$_bound_shas")"; n="$(jq -R -c -s 'split("\n") | map(select(length > 0))' <"$named_file")"; PR_LIST_JQ_ARGS=(--argjson jmap "$jen_map" --arg jstatus "$jen_status" --argjson shamap "${s:-null}" --argjson named "${n:-[]}"); } # $1 = this state's raw Bitbucket rows
4605
+ PR_LIST_BIND_FN=_bb_jen_bind
4337
4606
  pr_list_states bitbucket "$limit" "$bb_states" '.[] |
4338
- ($jmap[.source.branch.name] // null) as $jentry |
4607
+ ($jmap[.source.branch.name]) as $colour | (($colour.checks == "green" or $colour.checks == "failing")) as $ambiguous | (.source.branch.name) as $head | ((.source.commit.hash // "") != "") as $hasSha | (($named | index($head)) != null) as $wasNamed | ($shamap[.source.branch.name] // (if ($ambiguous and $hasSha and ($wasNamed | not)) then null else $colour end) // null) as $jentry |
4608
+ # A ROW `$jentry == null` WITH `$ambiguous` NEVER GOT A JENKINS
4609
+ # ANSWER THIS PASS — past the cap, or a lookup that broke early.
4610
+ # Distinct from Jenkins naming "unknown" itself — own field
4611
+ # rather than the same `checks` word (`bitbucket-jenkins-a-pr-list-row`).
4339
4612
  {
4340
4613
  number:.id, title:.title,
4341
4614
  state:(if .state=="DECLINED" then "CLOSED" else .state end),
@@ -4343,29 +4616,24 @@ case "$op" in
4343
4616
  draft:(.draft // false),
4344
4617
  checks:(
4345
4618
  if $jstatus != "ok" then "unknown"
4346
- elif $jentry == null then "none"
4619
+ elif $jentry == null then (if $ambiguous then "unknown" else "none" end)
4347
4620
  else $jentry.checks
4348
4621
  end),
4349
4622
  mergeable:"unknown",
4350
4623
  review:"",
4351
4624
  url:(.links.html.href // ""),
4352
- updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),
4625
+ updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),checksSha:($jentry.checksSha // ""),
4353
4626
  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 $?
4627
+ failing_checks:(if $jentry != null and $jentry.checks == "failing" then [$jentry.job] else [] end), base:(.destination.branch.name // "")
4628
+ } + (if $jstatus == "ok" and $ambiguous and $jentry == null then {checksLookup:"skipped"} else {} end)' "${bb_cmd[@]}" | bb_fold_mergeable_stream || exit $?
4629
+ PR_LIST_BIND_FN=""
4360
4630
  else
4361
4631
  # Bitbucket without Jenkins: checks remain unknown
4362
- PR_LIST_JQ_ARGS=()
4363
4632
  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 $?
4633
+ '.[] | {number:.id,title:.title,state:(if .state=="DECLINED" then "CLOSED" else .state end),head:.source.branch.name,draft:(.draft // false),checks:"unknown",mergeable:"unknown",review:"",url:(.links.html.href // ""),updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),author:(.author.nickname // ""),failing_checks:[],base:(.destination.branch.name // "")}' \
4634
+ "${bb_cmd[@]}" | bb_fold_mergeable_stream || exit $?
4366
4635
  fi
4367
4636
  else
4368
- PR_LIST_JQ_ARGS=()
4369
4637
  pr_list_states bitbucket "$limit" "$bb_states" \
4370
4638
  '.[] | {number:.id,title:.title,state:(if .state=="DECLINED" then "CLOSED" else .state end),head:.source.branch.name,author:(.author.nickname // "")}' \
4371
4639
  "${bb_cmd[@]}" || exit $?
@@ -4428,35 +4696,16 @@ case "$op" in
4428
4696
  startedAt:.startedAt, url:.url}' 2>/dev/null || true
4429
4697
  ;;
4430
4698
  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).
4699
+ # THE BRANCH'S BUILD HISTORY, newest first, read through
4700
+ # `jenkins_sha_runs` with no sha — the REST call `run-for-sha` and
4701
+ # `runs-for-sha` make. `startedAt` and `url` are Jenkins' own fields.
4439
4702
  #
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
4703
+ # CONCLUSION IS HOST-NEUTRAL, as in the GitHub arm above: Jenkins' raw
4704
+ # `.result` (`SUCCESS`/`FAILURE`/...), and the `status` (`in_progress`)
4705
+ # while a build runs — not the `checks` word the colour table settles
4706
+ # for `pr-list --rich`.
4707
+ _jen_all=$(jenkins_sha_runs runs "$branch" "$limit" "") || exit $?
4708
+ printf '%s' "$_jen_all" | jq -c '.[] | {workflow:.workflow, conclusion:(.conclusion // .status), startedAt:.startedAt, url:.url}' 2>/dev/null || true
4460
4709
  ;;
4461
4710
  *)
4462
4711
  ci_unaskable runs "$_ci"
@@ -4602,7 +4851,7 @@ case "$op" in
4602
4851
  # Slurped via stdin, never `--argjson`: that flag caps at 128 KB on Linux.
4603
4852
  _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
4853
  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
4854
+ '$match[0] + {jobs: [$run[0].jobs[] | {conclusion, startedAt, completedAt, steps: [(.steps // [])[].conclusion]}]}' || exit 4
4606
4855
  ;;
4607
4856
 
4608
4857
  issue-list)
@@ -4617,7 +4866,7 @@ case "$op" in
4617
4866
  # of them reproduces `an-outage-is-not-an-answer` — a board that says "no
4618
4867
  # issues" because it could not reach the tracker is stating a fact it does
4619
4868
  # not have.
4620
- limit=""; state="open"; since=""; page_token=""; paged=""
4869
+ limit=""; state="open"; since=""; page_token=""; paged=""; label=""; fix_version=""; title_has=""
4621
4870
  while [ $# -gt 0 ]; do
4622
4871
  case "$1" in
4623
4872
  --limit) limit="${2:?}"; shift 2 ;;
@@ -4625,13 +4874,16 @@ case "$op" in
4625
4874
  --since) since="${2:?}"; shift 2 ;;
4626
4875
  --page-token) page_token="${2:?}"; shift 2 ;;
4627
4876
  --paged) paged=1; shift ;;
4877
+ --label) label="${2:?}"; shift 2 ;;
4878
+ --fix-version) fix_version="${2:?}"; state=version; shift 2 ;;
4879
+ --title-has) title_has="${2:?}"; shift 2 ;;
4628
4880
  *) die "issue-list: unknown arg $1" ;;
4629
4881
  esac
4630
4882
  done
4631
4883
  # `--since` is spliced into a JQL string and a search qualifier, so its shape
4632
4884
  # 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>"
4885
+ [[ "$state" =~ ^(open|closed|inbox|changed|version)$ ]] || die "issue-list: --state is open, closed, inbox, changed or version, not '$state'"
4886
+ [[ "$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
4887
  limit_args=()
4636
4888
  [ -n "$limit" ] && limit_args=(--limit "$limit")
4637
4889
  # WHO LISTS THESE ISSUES IS ASKED ONCE, HERE, BEFORE THE ARMS — after the
@@ -4643,6 +4895,7 @@ case "$op" in
4643
4895
  # asked at all* — a configuration a person fixes, not a call to retry.
4644
4896
  # NOTHING HAS BEEN SPENT: no `gh`, no `bb`, no curl has run yet.
4645
4897
  [ "${source_said%%$'\t'*}" != nobody ] || { echo "plot-host: ${source_said#*$'\t'}" >&2; exit 4; }
4898
+ [ "$state" != version ] || [ "$source_said" = $'tracker\tjira' ] || { echo "plot-host: only a Jira tracker has fix versions" >&2; exit 4; }
4646
4899
  if [ "$source_said" = $'tracker\tjira' ]; then
4647
4900
  # Jira, resolved through the REST API — DISPATCHED ON `Tracker`, never on
4648
4901
  # `backend()`: a Bitbucket repo tracking in Jira is the normal enterprise
@@ -4654,6 +4907,7 @@ case "$op" in
4654
4907
  # the board. `PLOT_JIRA_JQL` overrides it for a team that wants a wider or
4655
4908
  # narrower inbox. ORDER BY created DESC so the newest ticket is first, the
4656
4909
  # same order `createdAt` gives the GitHub arm.
4910
+ { [ -z "$label" ] && [ -z "$title_has" ]; } || { echo "plot-host: jira cannot list issues by label or search by title" >&2; exit 4; }
4657
4911
  jira_require_config
4658
4912
  # `Ticket prefixes` SCOPES THE DEFAULT to this repository's projects. The
4659
4913
  # default alone scopes by person and by state, so on a shared instance it
@@ -4677,6 +4931,18 @@ case "$op" in
4677
4931
  # closed reads keep `assignee = currentUser()` only where `$scope` is
4678
4932
  # empty. The inbox read below keeps it unconditionally, and the scope too.
4679
4933
  person=""; [ -n "$scope" ] || person="assignee = currentUser() AND "
4934
+ # THE CLOSED, CHANGED AND VERSION READS REQUIRE `Ticket prefixes`: an
4935
+ # unscoped `resolved >=`, `updated >=` or `fixVersion =` query reads every
4936
+ # project on the instance, the hazard `tracker_projects` measured.
4937
+ [ -n "$scope" ] || ! [[ "$state" =~ ^(closed|changed|version)$ ]] || { echo "plot-host: $state Jira issues need 'Ticket prefixes' declared; an unscoped $state query reads the whole instance" >&2; exit 4; }; if [ "$state" = version ]; then found=""; for p in $projects; do vbody="$(jira_ask "/rest/api/2/project/$p/versions")" || exit $?; [ "$(jq --arg n "$fix_version" 'any(.[]; .name == $n)' <<<"$vbody")" = true ] && found=1; done; [ -n "$found" ] || { echo "plot-host: version-not-found: $fix_version" >&2; exit 4; }; fi
4938
+ # A VERSION READ EXISTS BEFORE IT IS SEARCHED: `fixVersion = "<name>"` alone
4939
+ # matches nothing for a name Jira has never heard of and still exits 0 with
4940
+ # no rows (measured 2026-10-21) — the exact silent empty answer this guard
4941
+ # exists to refuse. `version-list` per `Ticket prefixes` project is the
4942
+ # same read `versionRead` (tracker-jira.ts) makes to decide the same
4943
+ # question, so a same-named version outside those projects still counts as
4944
+ # unknown. A failed list (`|| exit $?`) propagates rather than reading as
4945
+ # not-found: absent is not false.
4680
4946
  # PLOT_JIRA_JQL STILL WINS OVER BOTH. Teams worked around this bug with
4681
4947
  # their own JQL; an override that stopped overriding would break exactly
4682
4948
  # the people who noticed the problem first.
@@ -4693,21 +4959,47 @@ case "$op" in
4693
4959
  # THE CLOSED READ REQUIRES `Ticket prefixes` AND READS NOT PLOT_JIRA_JQL.
4694
4960
  # An unscoped `resolved >=` query reads the whole instance — the hazard
4695
4961
  # `tracker_projects` measured for the open read — so with none declared
4696
- # the read exits 4 before any curl. `jira_require_config` follows. The
4962
+ # the read exits 4 before any curl, at the guard above. The
4697
4963
  # closed read is always paged: a page is ISSUE_PAGE_ROWS, and the
4698
4964
  # TypeScript adapter walks the pages, so this arm holds no loop. JQL dates take
4699
4965
  # `yyyy-MM-dd` or `yyyy-MM-dd HH:mm`, so the ISO `since` is cut to the
4700
4966
  # shape it has: a date-only `since` sends the date alone. JQL takes no
4701
4967
  # offset, so Jira reads the time in the reader's profile zone. Its
4702
4968
  # 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
4969
  when="${since:0:10} ${since:11:5}"; jql="resolved >= \"${when% }\"${scope} ORDER BY resolved DESC"
4705
4970
  fields="$fields,resolutiondate"; paged=1
4706
4971
  # THE D23 INBOX READ: always person-scoped, and project-scoped by `$scope`
4707
4972
  # like the open read, so *Waiting on you* shows the reader's own tickets of this repository's projects.
4708
4973
  elif [ "$state" = inbox ]; then jql="${PLOT_JIRA_JQL:-assignee = currentUser() AND resolution = EMPTY${scope} ORDER BY created DESC}"
4974
+ # THE CHANGED READ IS GATED LIKE THE CLOSED READ, for the same reason: an
4975
+ # unscoped `updated >=` query reads the whole instance. It asks `updated`
4976
+ # rather than `resolved`, since a changed row may still be open, and
4977
+ # carries `updatedAt` so the adapter's fold can compare it. It sends
4978
+ # `since` as a RELATIVE `-Nm`, the minutes from `since` to now plus 5:
4979
+ # Jira reads an absolute JQL time in the reader's profile zone, so a UTC
4980
+ # `since` cut to `yyyy-MM-dd HH:mm` starts hours late for a reader behind
4981
+ # UTC, and a relative time names the same instant in every zone. The 5
4982
+ # minutes cover clock skew; the fold drops the rows read twice.
4983
+ elif [ "$state" = changed ]; then
4984
+ 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
4985
+ # THE VERSION READ, gated with the closed read above: `fixVersion = "<name>"`
4986
+ # alone matches a same-named version in every project on a shared
4987
+ # instance. The name is escaped for a JQL string literal.
4988
+ elif [ "$state" = version ]; then jql="fixVersion = \"$(printf '%s' "$fix_version" | sed 's/\\/\\\\/g; s/"/\\"/g')\"${scope} ORDER BY created DESC"; paged=1
4709
4989
  fi
4710
- [ -z "$paged" ] || { max="${limit:-$ISSUE_PAGE_ROWS}"; [ "$max" -le "$ISSUE_PAGE_ROWS" ] || max="$ISSUE_PAGE_ROWS"; }
4990
+ # AN UNPAGED READ'S --limit ABOVE ONE PAGE IS REFUSED, NOT CLAMPED. Open
4991
+ # and inbox are the only states still unpaged here — closed and changed
4992
+ # forced `paged=1` above. Jira caps maxResults at 100 itself, so an
4993
+ # unpaged `--limit 200` silently returned 100 rows with no sign the other
4994
+ # 100 existed (measured 2026-10-21, ewz-kus-portal). Exit 2 is new here —
4995
+ # this arm otherwise uses `die` (1) for usage and 3/4 for host states —
4996
+ # because a stderr warning is lost wherever stderr is discarded, and the
4997
+ # three-outcomes rule above says a partial answer must not look like a
4998
+ # complete one. Checked BEFORE any curl: nothing is spent on a call this
4999
+ # refuses. `-gt`, not `-ge`: a full single page (100) is still one page
5000
+ # and must still answer. A non-numeric `--limit` skips this guard and
5001
+ # reaches Jira as an invalid `maxResults` instead — not this guard's job.
5002
+ if [ -n "$paged" ]; then max="${limit:-$ISSUE_PAGE_ROWS}"; [ "$max" -le "$ISSUE_PAGE_ROWS" ] || max="$ISSUE_PAGE_ROWS"; else [[ "$max" =~ ^[0-9]+$ ]] && [ "$max" -gt "$ISSUE_PAGE_ROWS" ] && { echo "plot-host: issue-list: --limit $limit exceeds one Jira page ($ISSUE_PAGE_ROWS); pass --paged to read it a page at a time" >&2; exit 2; }; fi
4711
5003
  token_args=(); [ -z "$page_token" ] || token_args=(--data-urlencode "nextPageToken=$page_token")
4712
5004
  # jq builds the query string so a JQL with spaces/quotes is encoded once,
4713
5005
  # not hand-escaped. --data-urlencode via curl -G keeps the token out of the
@@ -4717,7 +5009,14 @@ case "$op" in
4717
5009
  --data-urlencode "jql=$jql" \
4718
5010
  --data-urlencode "fields=$fields" \
4719
5011
  --data-urlencode "maxResults=$max" \
4720
- ${token_args[@]+"${token_args[@]}"})" || exit $?
5012
+ ${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
5013
+ # AN UNPAGED OPEN OR INBOX READ NEVER PRINTS ITS OWN "more rows exist"
5014
+ # signal — a paged read's `{"nextPageToken":…}` line IS that signal, and
5015
+ # printing it here too would duplicate it (open question 2). So this is
5016
+ # the only place that reads the response's own `nextPageToken` for an
5017
+ # unpaged read, on stderr, one line, before `$body` is reprojected below.
5018
+ # `// ""` reads a missing key and an empty one alike as "no more pages" —
5019
+ # a full page with no token (50 of 50) is Jira's own answer, not "cut".
4721
5020
  # `number` is the Jira KEY (PROJ-123), a string — #447 taught the parser to
4722
5021
  # read that form. `url` is built from the base + /browse/<key>; Jira's
4723
5022
  # search payload carries no browse URL, and the base is ours to know
@@ -4741,7 +5040,7 @@ case "$op" in
4741
5040
  createdAt: (.fields.created // ""),
4742
5041
  status: (.fields.status.name // ""),
4743
5042
  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)),
5043
+ } + (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
5044
  (select($paged == "1") | (.nextPageToken // empty) | {nextPageToken: .})'
4746
5045
  elif [ "$be" = "github" ]; then
4747
5046
  # `gh issue list` — not `gh api /issues`. On GitHub every PR IS an issue,
@@ -4760,15 +5059,37 @@ case "$op" in
4760
5059
  # keeps what closed since `$since`. GitHub search has no close-date sort
4761
5060
  # (`sort:closed-desc` was measured ignored, 2026-10-13), so the adapter
4762
5061
  # 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[@]}"} \
5062
+ #
5063
+ # A CHANGED READ ASKS `--state all`, SINCE IT CAN RETURN EITHER STATE, so
5064
+ # `status`/`statusCategory` are projected from EACH ROW'S OWN `.state`
5065
+ # rather than from `$gh_state` — the one read here where the issue
5066
+ # itself, not the call, says what it is. `updatedAt` rides along so the
5067
+ # adapter's fold can compare it the way `foldIssueRows` already does.
5068
+ # `--title-has` IS OPEN-ONLY AND NEEDS NO CHANGED/CLOSED SEARCH TERM
5069
+ # BESIDE IT: `gh` keeps only its LAST `--search` flag rather than ANDing
5070
+ # several, so a state that already uses one here is refused instead of
5071
+ # silently losing the title filter (open issues is the lookup's only use).
5072
+ [ -z "$title_has" ] || [ "$gh_state" = open ] || die "issue-list: --title-has only works with --state open"
5073
+ gh_json="number,title,url,createdAt,assignees,issueType"; search_args=(); ask_state="$gh_state"
5074
+ [ -z "$label" ] || search_args=(--label "$label")
5075
+ if [ "$gh_state" = changed ]; then gh_json+=",updatedAt,state,closedAt"; ask_state=all; search_args+=(--search "updated:>=$since")
5076
+ elif [ "$gh_state" != open ]; then gh_json+=",closedAt"; search_args+=(--search "closed:>=$since")
5077
+ # TITLE SEARCH NARROWS, IT DOES NOT REPLACE THE LABEL FILTER: both are
5078
+ # qualifiers `gh` combines in one `--search` string, so a backlog's
5079
+ # label stays the safety net while the title cuts the read to the one PR
5080
+ # asked about. Quoted so a PR number with no other digit around it cannot
5081
+ # match a longer one; `findOpenReviewIssue` still checks every candidate,
5082
+ # since GitHub's search is not an exact title match.
5083
+ elif [ -n "$title_has" ]; then search_args+=(--search "in:title \"$title_has\""); fi
5084
+ if out="$(gh issue list --state "$ask_state" ${limit_args[@]+"${limit_args[@]}"} \
4766
5085
  ${search_args[@]+"${search_args[@]}"} --json "$gh_json" 2>"$HOST_ERR")"; then
4767
5086
  rm -f "$HOST_ERR"
4768
5087
  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"
5088
+ '.[] | ((.state // $status) | ascii_downcase) as $actual |
5089
+ {number:.number,title:.title,url:(.url // ""),createdAt:(.createdAt // ""),
5090
+ status:$actual,statusCategory:(if $actual == "open" then "To Do" else "Done" end),assignees:[.assignees[]?.login]}
5091
+ + (if .updatedAt then {updatedAt:.updatedAt} else {} end) + (if .issueType.name? then {type:.issueType.name} else {} end)
5092
+ + (if $actual == "closed" then {closedAt:(.closedAt // "")} else {} end)' <<<"$out"
4772
5093
  # `gh` pages by 100 inside ONE process and the wrapper records one call
4773
5094
  # per process, so each page past the first is recorded here.
4774
5095
  jq -r "[range(1; length / $ISSUE_PAGE_ROWS | ceil)] | .[]" <<<"$out" | while read -r _; do budget_record_call github github graphql; done
@@ -4787,9 +5108,10 @@ case "$op" in
4787
5108
  # after parsing; (3) the list carries no per-issue URL, so `url` is "" —
4788
5109
  # the same answer the header documents for a host that omits it.
4789
5110
  #
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; }
5111
+ # A CLOSED OR CHANGED READ IS EXIT 4: `bb issue list` prints no closing or
5112
+ # update date, so there is nothing honest to return for either. It runs
5113
+ # before any `bb` command.
5114
+ { [ "$state" = open ] && [ -z "$label" ] && [ -z "$title_has" ]; } || { echo "plot-host: bitbucket cannot list closed or changed issues, issues by label, or issues by title" >&2; exit 4; }
4793
5115
  bb_assert_issue_version || exit $?
4794
5116
  # `--state new,open` is bb's own default for `issue list` and is what
4795
5117
  # "open tracker issues" means; stated explicitly so a bb default change
@@ -4797,12 +5119,9 @@ case "$op" in
4797
5119
  # call (the request-budget comment in fleet.ts counts exactly this).
4798
5120
  raw="$(bb issue list --state new --state open 2>&1)"; rc=$?
4799
5121
  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
5122
+ # bb's error is on stdout, now folded into `raw`. Report it and choose
5123
+ # 4-vs-3 from its wording — never parse it as an issue (Done-when 6).
5124
+ [ "$rc" -eq 0 ] || { echo "plot-host: $raw" >&2; exit "$(bb_issue_exit_code "$(tr '[:upper:]' '[:lower:]' <<<"$raw")")"; }
4806
5125
  # A row is `#NNN <STATE> <title> by <reporter>`. Anchor on the `#NNN`
4807
5126
  # prefix (the header line ` :: Showing …` has none and is skipped for
4808
5127
  # free), lift the number, strip the known state badge word, then drop the
@@ -4876,18 +5195,21 @@ case "$op" in
4876
5195
  # the board. jira_check turns that 404 into exit 3 with empty stdout.
4877
5196
  jira_require_config
4878
5197
  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" '{
5198
+ -G --data-urlencode "fields=summary,description,status")" || exit $?
5199
+ # `state` FOLLOWS issue-list's OWN WORD: `statusCategory.name == "Done"`
5200
+ # is closed, same mapping as the list's open/closed reader — a second
5201
+ # vocabulary here would drift from the one issue-list already keeps.
5202
+ printf '%s' "$body_json" | jq -c --arg base "$(tracker_base_url)" '{
4882
5203
  number: .key,
4883
5204
  title: (.fields.summary // ""),
4884
5205
  body: (.fields.description // ""),
4885
- url: ($base + "/browse/" + .key)
5206
+ url: ($base + "/browse/" + .key),
5207
+ state: (if .fields.status.statusCategory.name == "Done" then "closed" else "open" end)
4886
5208
  }'
4887
5209
  elif [ "$be" = "github" ]; then
4888
- if out="$(gh issue view "$num" --json number,title,body,url 2>"$HOST_ERR")"; then
5210
+ if out="$(gh issue view "$num" --json number,title,body,url,state 2>"$HOST_ERR")"; then
4889
5211
  rm -f "$HOST_ERR"
4890
- jq -c '{number:.number,title:(.title // ""),body:(.body // ""),url:(.url // "")}' <<<"$out"
5212
+ jq -c '{number:.number,title:(.title // ""),body:(.body // ""),url:(.url // ""),state:((.state // "open") | ascii_downcase)}' <<<"$out"
4891
5213
  else
4892
5214
  # NO miss/fail split here, and that is deliberate. `host_miss_or_fail`
4893
5215
  # exists where an absent subject is a NORMAL answer — a branch with no
@@ -4916,15 +5238,19 @@ case "$op" in
4916
5238
  bb_assert_issue_version || exit $?
4917
5239
  raw="$(bb issue view "$num" 2>&1)"; rc=$?
4918
5240
  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
5241
+ [ "$rc" -eq 0 ] || { echo "plot-host: $raw" >&2; exit "$(bb_issue_exit_code "$(tr '[:upper:]' '[:lower:]' <<<"$raw")")"; }
4923
5242
  # Title is the first line. URL is lifted from the footer, which is bb's
4924
5243
  # only place that prints one for a viewed issue — so the contract's `url`
4925
5244
  # is real here even though issue-list's is "".
4926
5245
  title="$(sed -n '1p' <<<"$raw")"
4927
5246
  url="$(grep -oE 'https?://[^[:space:]]+' <<<"$(grep -F 'View this issue on Bitbucket' <<<"$raw")" | head -1)"
5247
+ # Line 2 is `<STATE> • <reporter> opened <createdOn>` — the same badge
5248
+ # word `issue-list` strips from its own row, read here instead of
5249
+ # discarded. RESOLVED/CLOSED close it; everything else (including states
5250
+ # this vocabulary has no word for) stays open, the same default
5251
+ # issue-list's mapping leaves for an unmapped badge.
5252
+ bb_state="$(sed -n '2p' <<<"$raw" | sed -E 's/^([A-Z ]+)[[:space:]]*•.*$/\1/; s/[[:space:]]+$//')"
5253
+ case "$bb_state" in RESOLVED|CLOSED) state=closed ;; *) state=open ;; esac
4928
5254
  # Body is the block between the metadata head and the footer. The head is
4929
5255
  # the title + the two fixed meta lines (state, Type:) plus an optional
4930
5256
  # Component/Milestone/Version line; the tail is the footer. This is the
@@ -4946,8 +5272,8 @@ case "$op" in
4946
5272
  { lines[NR]=$0; if ($0 ~ /[^[:space:]]/) { if (!first) first=NR; last=NR } }
4947
5273
  END { for (i=first; i<=last; i++) print lines[i] }
4948
5274
  ' <<<"$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}'
5275
+ jq -cn --argjson number "$num" --arg title "$title" --arg body "$body" --arg url "$url" --arg state "$state" \
5276
+ '{number:$number,title:$title,body:$body,url:$url,state:$state}'
4951
5277
  fi
4952
5278
  ;;
4953
5279
 
@@ -5007,13 +5333,45 @@ case "$op" in
5007
5333
  # verbatim; prints Jira's JSON answer.
5008
5334
  # github-issues <title> <body> [--label <label>...]; prints the new
5009
5335
  # 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 ;;
5336
+ # Exit 4, with the reason, for any other source — dispatched on the domain's
5337
+ # `issueSource` answer like issue-list, never on `tracker_scheme`.
5338
+ source_said="$(issue_source)" || exit 1
5339
+ case "$source_said" in
5340
+ $'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 $? ;;
5341
+ $'tracker\tgithub-issues') gh issue create --title "${1:?issue-open needs a title}" --body "${2-}" "${@:3}" 2>"$HOST_ERR" || gh_fail ;;
5342
+ *) echo "plot-host: issue-open: ${source_said#*$'\t'}" >&2; exit 4 ;;
5015
5343
  esac ;;
5016
5344
 
5345
+ issue-label|issue-comment|issue-close)
5346
+ # THE PLAN-STATE WRITES, and one-way: Plot sets a `plan:*` label, keeps one
5347
+ # comment per issue and closes the issue at release; nothing reads any back.
5348
+ # issue-label <n> <add> [<remove,...>] adds one label, removes the rest
5349
+ # issue-comment <n> <marker> <body> edits the comment holding <marker>, else posts; an empty <marker> always posts
5350
+ # issue-close <n>
5351
+ # GitHub issues only, dispatched on `issue_source` like issue-open. Exit 4,
5352
+ # with the reason, for a source that cannot be asked.
5353
+ num="${1:?$op needs an issue number}"; source_said="$(issue_source)" || exit 1
5354
+ [ "$be" = github ] && { [ "$source_said" = git-host ] || [ "$source_said" = $'tracker\tgithub-issues' ]; } || { echo "plot-host: $op: ${source_said#*$'\t'}" >&2; exit 4; }
5355
+ case "$op" in
5356
+ issue-label) gh issue edit "$num" --add-label "${2:?issue-label needs a label}" ${3:+--remove-label "$3"} >/dev/null 2>"$HOST_ERR" || gh_fail ;;
5357
+ issue-close) gh issue close "$num" >/dev/null 2>"$HOST_ERR" || gh_fail ;;
5358
+ issue-comment)
5359
+ cid=""; [ -z "${2-}" ] || cid="$(gh api --paginate "repos/{owner}/{repo}/issues/$num/comments" 2>"$HOST_ERR" | jq -rs --arg m "$2" '[.[][] | select(.body | contains($m))][0].id // empty')" || gh_fail
5360
+ if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${3-}" >/dev/null 2>"$HOST_ERR" || gh_fail
5361
+ else gh issue comment "$num" --body "${3-}" >/dev/null 2>"$HOST_ERR" || gh_fail; fi ;;
5362
+ esac
5363
+ rm -f "$HOST_ERR" ;;
5364
+
5365
+ # The projects `Ticket prefixes` scopes to, one per line, honoring
5366
+ # PLOT_TICKET_PREFIXES — the one answer the TypeScript connector asks.
5367
+ ticket-projects) tracker_projects ;;
5368
+
5369
+ version-list)
5370
+ # A Jira project's versions, unfiltered — see the usage header.
5371
+ source_said="$(issue_source)" || exit 1; [ "$source_said" = $'tracker\tjira' ] || { echo "plot-host: version-list needs 'Tracker: jira'" >&2; exit 4; }
5372
+ jira_require_config; body="$(jira_ask "/rest/api/2/project/${1:?version-list needs a project key}/versions")" || exit $?
5373
+ printf '%s' "$body" | jq -c '.[] | {name, released: (.released // false), releaseDate: (.releaseDate // null)}' || exit 3 ;;
5374
+
5017
5375
  pr-body)
5018
5376
  num="${1:?pr-body needs a PR number}"; shift
5019
5377
  body=""
@@ -5190,8 +5548,6 @@ case "$op" in
5190
5548
  # decides how much to trust it; a `throttled` observed during the session
5191
5549
  # is what corrects it.
5192
5550
  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
5551
  fi
5196
5552
  ;;
5197
5553
 
@@ -5292,18 +5648,26 @@ case "$op" in
5292
5648
  # `plot-commit-status.mjs` holds the GitHub App JWT/installation-token
5293
5649
  # exchange; `plot-bitbucket-commit-status.mjs` holds the Bitbucket state
5294
5650
  # 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; }
5651
+ # parsed from `origin` by the `plot-bitbucket-slug.mjs` bundle (never from
5652
+ # `bb`, which would mean asking whichever identity is signed in on this
5653
+ # machine). The bundle reads a port after the host of a scheme'd URL
5654
+ # (`ssh://git@altssh.bitbucket.org:443/ws/repo`) as a port, and the colon
5655
+ # of an scp-style remote (`git@bitbucket.org:12345/repo`) as the start of
5656
+ # the path, so a numeric workspace survives. An empty slug is `unsupported`.
5657
+ [ "$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
5658
  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 $?
5659
+ node "$here/plot-commit-status.mjs" --repo "$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null || echo GH_REPO_VIEW_FAILED)" "$@" || exit $?
5304
5660
  ;;
5305
5661
 
5662
+ pr-comment)
5663
+ # KEYED BY PR NUMBER, NOT A SHA — unlike commit-status, this writes through
5664
+ # the signed-in CLI identity, so it needs no App credentials and no Node
5665
+ # helper.
5666
+ [ "$be" = "github" ] || { echo "plot-host: pr-comment: bitbucket has no verified pr-comment write" >&2; exit 4; }; num="${1:?pr-comment needs a PR number}"; cid=""
5667
+ [ -z "${3-}" ] || cid="$(gh api --paginate "repos/{owner}/{repo}/issues/$num/comments" 2>"$HOST_ERR" | jq -rs --arg m "$3" '[.[][] | select(.body | contains($m))][0].id // empty')" || gh_fail
5668
+ if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${2:?pr-comment needs a body}" >/dev/null 2>"$HOST_ERR" || gh_fail; else gh pr comment "$num" --body "${2:?pr-comment needs a body}" >/dev/null 2>"$HOST_ERR" || gh_fail; fi; rm -f "$HOST_ERR" ;;
5669
+
5306
5670
  *)
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)"
5671
+ die "unknown op '$op' (backend|default-branch|pr-state|pr-create|pr-merge|pr-list|issue-list|issue-view|issue-status|issue-open|issue-label|issue-comment|issue-close|version-list|pr-body|pr-review|rate-limit|limit|ci-limit|spend-rate|commit-status|pr-comment)"
5308
5672
  ;;
5309
5673
  esac