@futurelastic/colab-handbook 1.21.0-rc.5 → 1.21.0-rc.7

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/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.21.0-rc.5"
36
+ "version": "1.21.0-rc.7"
37
37
  }
@@ -110,7 +110,7 @@ check that reads one of these files is that tool's behaviour, documented with th
110
110
  | `ci-node-heavy.yml`, `ci-python-heavy.yml`, `ci-laravel-heavy.yml` | `.github/workflows/ci-heavy.yml` | The heavy lane beside the matching `ci-<stack>.yml` (above) | `schedule` + `workflow_dispatch` + `workflow_call`, never a push. **Still a copy** (#724 kept it one: it runs nightly and on candidates, never per merge, so it is not what drifted, and its plan gate is per-repo). Its toolchain resolution follows the same precedence as the reusable light lane's, and the `secrets` job's gitleaks install and `GITLEAKS_VERSION` follow its `gitleaks` job — keep them in step. `TRUNK` is an edit point. |
111
111
  | `ci-python.yml` | `.github/workflows/ci.yml` | Python: FastAPI/Flask services, CLIs, libraries | A **caller** of `ci-light.yml` (#724): byte-compile, ruff and mypy in `quick`, pytest in `full`, each only if installed. The call resolves Python from `project.yml` → `.python-version`/`requires-python` → **fails**. `requirements.txt` does not count. **Hybrid** Python+Node repo: `toolchain: python,node` in the same call — see the template header. Opt-in `Migration round-trip` job, as in `ci-node.yml`. |
112
112
  | `release-tag.yml` | `.github/workflows/release.yml` | Any repo cutting `v*.*.*` releases | Triggers on tag push. Publishes a grouped GitHub Release — a `-rc.N` tag as a pre-release, every summary since the previous *final* tag. No toolchain, no deploy; its header shows the `!v*.*.*-*` exclusion a deploy trigger needs. |
113
- | `release-auto.yml` | `.github/workflows/release-auto.yml` | A repo whose release tags land on `main` (`trunk: main`, `deploy: tag` or `none`) and whose §6 release route cuts candidates | Runs `colab release cut --auto` after CI goes green on main — at the sha that CI run tested (`--sha`, #622), even once main has moved on — and `colab release finalize --auto` daily — plus an hourly run that re-tries only a refused cut, once the fetched CLI has moved within `RETRY_WINDOW_MINUTES` or a run at main's head was cancelled (#547) — from a handbook ref (`HANDBOOK_REF` — the `stable` channel by default, `next` for the fast channel, or an exact tag to freeze; #445) — the handbook's own copy runs its checkout's CLI instead, since it ships the CLI it releases with (#428). **Publishes the Release in the same run** — a tag pushed with `GITHUB_TOKEN` triggers no other workflow, so `release-tag.yml` would never fire for it. A refusal is a warning, not a red run. Reads and creates tags, and fast-forwards the release channels `next` / `stable` (branches naming the newest candidate / final, #445); never pushes a commit. The audit recognises any workflow running `release cut/finalize --auto` and warns when the route leaves candidates off, when it tags without publishing while a tag-push workflow waits, or when it commits. |
113
+ | `release-auto.yml` | `.github/workflows/release-auto.yml` | A repo whose release tags land on `main` (`trunk: main`, `deploy: tag` or `none`) and whose §6 release route cuts candidates | Runs `colab release cut --auto` after CI goes green on main — at the sha that CI run tested (`--sha`, #622), even once main has moved on — and `colab release finalize --auto` daily — plus an hourly run that re-tries only a refused cut, once the fetched CLI has moved within `RETRY_WINDOW_MINUTES` or a run at main's head was cancelled (#547). A first job, `decide`, skips the heavy job on a run with nothing to do: a red CI run, a CI run at a sha that already carries its tag, or an hourly run with nothing to retry (#735). It uses a handbook ref (`HANDBOOK_REF` — the `stable` channel by default, `next` for the fast channel, or an exact tag to freeze; #445) — the handbook's own copy runs its checkout's CLI instead, since it ships the CLI it releases with (#428). **Publishes the Release in the same run** — a tag pushed with `GITHUB_TOKEN` triggers no other workflow, so `release-tag.yml` would never fire for it. A refusal is a warning, not a red run. Reads and creates tags, and fast-forwards the release channels `next` / `stable` (branches naming the newest candidate / final, #445); never pushes a commit. The audit recognises any workflow running `release cut/finalize --auto` and warns when the route leaves candidates off, when it tags without publishing while a tag-push workflow waits, or when it commits. |
114
114
  | `forgejo-release-auto.yml` | `.forgejo/workflows/release-auto.yml` | A repo hosted on **Forgejo** (or Gitea) whose §6 release route cuts candidates, with the forge named in the machine config's `forges` (#678) | The Forgejo dialect of `release-auto.yml` (#681). It has no `workflow_run`: the job you append to your CI (in its header) dispatches it when CI ends green, with `source=ci-completed` and the sha it tested. It waits for CI at that sha (`colab ci-wait`), then runs `colab release cut --auto --sha`, which tags the candidate and publishes its pre-release through the forge's API. No `permissions:` blocks, full-URL `uses:`, the runner label from the `RELEASE_RUNNER` variable, verdicts printed to the log (Forgejo drops the step summary), no `jq`. A refusal stays green. No verdict is a red run. **No finalize step**: on a forge a final is a human's `release finalize` under the human bar, which also publishes the final's release, so no tag-push workflow is needed. Keep its `name:` equal to the file's base name, because the CLI drops its own statuses by that name. |
115
115
  | `dist-refs.yml` | `.github/workflows/dist-refs.yml` | A **private** repo shipping a **compiled** tool, installed as `npx github:<org>/<repo>#vX.Y.Z` ([CONVENTIONS §6, *Distribution*](../CONVENTIONS.md#distribution--one-install-surface-npx-442)) | `workflow_call`, called from the same run that cut the release tag (a tag pushed with `GITHUB_TOKEN` triggers nothing else). Takes one build artifact per `<os>-<arch>` and pushes each as an orphan commit at `refs/tags/dist/vX.Y.Z/<os>-<arch>` with a `SHA256SUMS`. Refuses a public or unreadable repository (a public compiled tool ships npm platform packages instead), a version that is not an existing tag, and a missing platform — before pushing any. Never moves a dist ref that exists. |
116
116
  | `npx-launcher.mjs` | anywhere in-repo (e.g. `bin/launch.mjs`), named by the root `package.json`'s `bin` | Pairs with `dist-refs.yml` | Node ≥ 18, zero dependencies, needs `git`. Reads the `#vX.Y.Z` npx installed, fetches that one dist ref with the same URL and credentials npx cloned with, verifies `SHA256SUMS`, installs to a stable per-user path (`$XDG_DATA_HOME`/`%LOCALAPPDATA%`), and execs it; `--print-path` prints that path. A **channel** committish (`#stable`, `#next`, #465) is resolved to the release tag on the commit npx installed, then installed as that version; any other branch is refused. Also the library `npx-service.mjs` imports. `*.mjs`, so `colab template npx-launcher.mjs --dest <path>` copies it stamped, `--dest` required. One edit point: `BIN` (defaults to the package name without its scope). |
@@ -189,9 +189,26 @@
189
189
  # Every other hourly run checks those and stops: no cut, no promotion, no finalize, so a held head is
190
190
  # not tagged sooner than the daily run would tag it, and a standing refusal is not re-announced every
191
191
  # hour. Nothing is stored between runs; the facts are re-read each time. EDIT: the cron string inside
192
- # RETRY_RUN (release job env) must stay byte-identical to the hourly `cron:` line, or no run is
192
+ # RETRY_RUN (the workflow `env:`) must stay byte-identical to the hourly `cron:` line, or no run is
193
193
  # recognised as a retry run — and the hourly run would then promote and finalize every hour.
194
194
  #
195
+ # A RUN WITH NOTHING TO DO ENDS IN SECONDS (#735). Most runs find nothing to do — the hourly run with
196
+ # nothing to retry, a CI re-run at a commit that already carries its tag, a red CI run — and each one
197
+ # used to take a runner and pay the full setup (full-history checkout, CLI fetch) before saying so. So
198
+ # the first job, `decide`, rules on the cases it can prove with a one-commit checkout and a tag list,
199
+ # and `release` (and with it `npm`, `npm-record`, `deploy` and your downloads jobs, which all need it)
200
+ # runs only when `decide` says there is work:
201
+ # workflow_run, CI not green no work — nothing is cut at a red sha
202
+ # workflow_run, the sha already carries a no work — the cut there is a no-op (#443), and a run
203
+ # release tag (vX.Y.Z or vX.Y.Z-rc.N) fired by CI does nothing but the cut and what it tags
204
+ # the hourly run the #547 retry step's verdict (it lives in `decide`)
205
+ # the daily run, a dispatch always work — promotion, finalize and the npm and
206
+ # downloads sweeps are the CLI's to rule on, and a dry
207
+ # run proves a fix only by running the whole job (#474)
208
+ # `decide` is a filter, never a second decider: it skips only where `release` is provably a no-op, and
209
+ # says "work" whenever it cannot read what it needs. It has no job-level `if:` and always concludes
210
+ # success, so a run that skips every other job still concludes success at main's sha (#435).
211
+ #
195
212
  # A REFUSAL IS NOT A FAILURE. `colab release cut --auto` refusing (nothing owed, a check
196
213
  # failed) is the ordinary output of most runs; it is printed to the run summary as a
197
214
  # warning and the job stays green, so a refusal never paints main red for `colab ship`.
@@ -221,7 +238,7 @@
221
238
  # owner's billing fails GitHub refuses a hosted job before it starts: main goes red, every landing
222
239
  # is refused until a human steps in — measured twice in a row on one adopting repo, where this was
223
240
  # the only workflow on main still on hosted runners. So:
224
- # private / internal repo `release` and `npm-record` run on the trunk class, `[self-hosted,
241
+ # private / internal repo `decide`, `release` and `npm-record` run on the trunk class, `[self-hosted,
225
242
  # trunk]` — the class your ci.yml's trunk jobs use (CONVENTIONS.md §7,
226
243
  # "Runner classes"); `deploy`, if you enable it, on its own restricted
227
244
  # deploy label. The runner needs git, node, gh and jq on its PATH
@@ -250,7 +267,7 @@ on:
250
267
  # hour is when scheduled runs queue longest.
251
268
  - cron: "17 3 * * *"
252
269
  # #547: the hourly RETRY run — cut only, only when the CLI moved or a run was displaced (header,
253
- # "A REFUSAL THE HANDBOOK FIXES"). Keep it byte-identical to the string in RETRY_RUN (release job env).
270
+ # "A REFUSAL THE HANDBOOK FIXES"). Keep it byte-identical to the string in RETRY_RUN (workflow `env:`).
254
271
  - cron: "47 * * * *"
255
272
  workflow_dispatch:
256
273
  # #474: a DRY RUN for a fix branch — see "DRY RUN ON A FIX BRANCH" in the header. A dispatch on
@@ -285,6 +302,9 @@ env:
285
302
  # it never fails the run (#480).
286
303
  HANDBOOK_REF: "stable"
287
304
  HANDBOOK_REPO: "https://github.com/futurelastic/colab-handbook.git"
305
+ # #547: 'true' on the hourly retry run, read by both jobs (#735). EDIT: the cron string here is
306
+ # byte-identical to the hourly `cron:` under `on.schedule`.
307
+ RETRY_RUN: ${{ github.event_name == 'schedule' && github.event.schedule == '47 * * * *' }}
288
308
  # A TRANSIENT UPSTREAM ERROR NEVER TURNS MAIN RED (#464). This run fires on every landing, and a
289
309
  # red run at main's head blocks every `colab ship` — so a GitHub / registry 5xx, a 429, a timeout
290
310
  # or a dropped connection must not fail a step that a plain re-run would pass. Every step that
@@ -354,13 +374,130 @@ env:
354
374
  }
355
375
 
356
376
  jobs:
377
+ # ---------------------------------------------------------------------------------------------
378
+ # decide (#735) — whether this run has any work, ruled on a one-commit checkout before any job that
379
+ # fetches history or the CLI starts. See "A RUN WITH NOTHING TO DO ENDS IN SECONDS" in the header.
380
+ decide:
381
+ name: Decide whether there is work
382
+ # No job-level `if:` and no `needs:` here, ever (#435): this job always runs and concludes success,
383
+ # which is what keeps the run from concluding `skipped` when it skips every other job. GitHub
384
+ # records a run whose every job a job-level `if:` skipped as `skipped` at that main sha, and
385
+ # `colab ship` reads any finished run that is neither success nor cancelled as "not green".
386
+ # EDIT: PRIVATE repo → the trunk class, [self-hosted, trunk] — the same label as `release` below
387
+ # (RUNNERS, above). ubuntu-latest only on a public repo.
388
+ runs-on: ubuntu-latest
389
+ permissions:
390
+ contents: read # list the tags (git ls-remote) over the checkout's origin
391
+ actions: read # the #547 retry reads this workflow's runs at main's head
392
+ outputs:
393
+ work: ${{ steps.work.outputs.work }}
394
+ retry: ${{ steps.retry.outputs.retry }}
395
+ env:
396
+ GH_TOKEN: ${{ github.token }}
397
+ # EDIT: how recent a move of the CLI still earns a retry (#547). Two hourly runs plus slack, so one
398
+ # scheduled run GitHub drops under load does not lose the retry; a second retry is a no-op.
399
+ RETRY_WINDOW_MINUTES: "130"
400
+ steps:
401
+ # One commit, no tags, no blobs outside .github: only what `git rev-parse HEAD` and `git ls-remote
402
+ # origin` need. EDIT: if your trunk is not `main`, name it here too (the same branch as below).
403
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
404
+ with:
405
+ ref: main
406
+ fetch-depth: 1
407
+ sparse-checkout: .github
408
+ # Left on: `git ls-remote origin` reads the tags with this job's read-only token.
409
+ persist-credentials: true
410
+
411
+ # #547: on the hourly retry run only — decide whether a cut is worth re-trying (header, "A REFUSAL
412
+ # THE HANDBOOK FIXES"). Ends green either way; retry=true is the hourly run's only work. A dry run
413
+ # never runs it (tools/lib/ci-cure.js DRY_RUN_CONDITIONAL_STEPS names it).
414
+ - name: Retry a refused cut once the CLI moved (#547)
415
+ id: retry
416
+ if: env.RETRY_RUN == 'true'
417
+ run: |
418
+ set -uo pipefail
419
+ eval "$RETRY_TRANSIENT"
420
+ decide() { echo "retry=$1" >> "$GITHUB_OUTPUT"; echo "Retry run (#547): $2" | tee -a "$GITHUB_STEP_SUMMARY"; exit 0; }
421
+ HEAD="$(git rev-parse HEAD)"
422
+ # #735: this checkout carries no tags, so they are read from origin. A list that cannot be read
423
+ # rules nothing out — the checks below decide.
424
+ TAGGED=""
425
+ if REFS="$(retry_transient git ls-remote --tags origin)"; then
426
+ TAGGED="$(awk -v h="$HEAD" '$1 == h && $2 ~ /^refs\/tags\/v/ { t = substr($2, 11); if (substr(t, length(t) - 2) == "^{}") t = substr(t, 1, length(t) - 3); print t; exit }' <<< "$REFS")"
427
+ fi
428
+ [ -z "$TAGGED" ] || decide false "main's head ${HEAD:0:7} already carries $TAGGED — nothing to retry."
429
+ # When the CLI reached HANDBOOK_REF: a channel moves onto a release tag's commit, so that
430
+ # tag's date is the move; a plain branch or an untagged commit falls back to the commit date.
431
+ # #735: the ref is fetched here with no blobs and no working tree — only its commit and the tags
432
+ # at it are read. A ref that cannot be fetched (one the handbook does not carry, #480) cannot
433
+ # rule a move out: the release job fetches the CLI, with its fallback, and re-tries the cut.
434
+ CLI_DIR="$RUNNER_TEMP/colab-handbook-ref"
435
+ fetch_ref() { rm -rf "$CLI_DIR"; git clone --quiet --depth 1 --filter=blob:none --no-checkout --branch "$HANDBOOK_REF" "$HANDBOOK_REPO" "$CLI_DIR"; }
436
+ retry_transient fetch_ref > /dev/null \
437
+ || decide true "could not fetch HANDBOOK_REF \"$HANDBOOK_REF\", so a move of the colab CLI cannot be ruled out and main's head ${HEAD:0:7} has no tag — re-trying the cut."
438
+ CLI_SHA="$(git -C "$CLI_DIR" rev-parse --short HEAD 2> /dev/null || echo unknown)"
439
+ MOVED="$(git -C "$CLI_DIR" for-each-ref --points-at HEAD --format='%(taggerdate:unix)' refs/tags 2> /dev/null | grep -E '^[0-9]+$' | sort -n | tail -n 1)"
440
+ [ -n "$MOVED" ] || MOVED="$(git -C "$CLI_DIR" log -1 --format=%ct HEAD 2> /dev/null || true)"
441
+ AGE=""; [ -n "$MOVED" ] && AGE=$(( $(date +%s) - MOVED ))
442
+ if [ -n "$AGE" ] && [ "$AGE" -le $(( ${RETRY_WINDOW_MINUTES:-130} * 60 )) ]; then
443
+ decide true "the colab CLI ($CLI_SHA) reached HANDBOOK_REF $(( AGE / 60 )) min ago and main's head ${HEAD:0:7} has no tag — re-trying the cut with it."
444
+ fi
445
+ # A run this one displaced: the newest OTHER run of this workflow at main's head, cancelled.
446
+ # An unreadable list re-tries rather than guessing — a cut with nothing owed is a no-op.
447
+ RUNS="$(retry_transient gh run list --workflow "$GITHUB_WORKFLOW" --commit "$HEAD" --limit 20 --json databaseId,conclusion,createdAt)" \
448
+ || decide true "could not list this workflow's runs at ${HEAD:0:7}, so a displaced run cannot be ruled out — re-trying the cut."
449
+ LAST="$(jq -r --arg me "${GITHUB_RUN_ID:-0}" '[.[] | select((.databaseId | tostring) != $me)] | sort_by(.createdAt) | last | .conclusion // ""' <<< "$RUNS" 2> /dev/null || echo unreadable)"
450
+ case "$LAST" in
451
+ cancelled) decide true "the last run at main's head ${HEAD:0:7} was cancelled (displaced from the shared concurrency group) — doing its cut." ;;
452
+ unreadable) decide true "could not read this workflow's runs at ${HEAD:0:7}, so a displaced run cannot be ruled out — re-trying the cut." ;;
453
+ esac
454
+ decide false "the colab CLI ($CLI_SHA) has not moved in the last ${RETRY_WINDOW_MINUTES:-130} min and no run at ${HEAD:0:7} was displaced — nothing to retry; the daily run cuts as usual."
455
+
456
+ # #735: the verdict the other jobs read — work=true whenever this job cannot prove the run is a
457
+ # no-op (header, "A RUN WITH NOTHING TO DO ENDS IN SECONDS"). Ends green either way.
458
+ - name: Decide whether this run has work
459
+ id: work
460
+ env:
461
+ EVENT: ${{ github.event_name }}
462
+ CONCLUSION: ${{ github.event.workflow_run.conclusion }}
463
+ RUN_SHA: ${{ github.event.workflow_run.head_sha }}
464
+ RETRY: ${{ steps.retry.outputs.retry }}
465
+ run: |
466
+ set -uo pipefail
467
+ eval "$RETRY_TRANSIENT"
468
+ decide() { echo "work=$1" >> "$GITHUB_OUTPUT"; echo "Work (#735): $2" | tee -a "$GITHUB_STEP_SUMMARY"; exit 0; }
469
+ case "${EVENT:-}" in
470
+ workflow_dispatch)
471
+ decide true "a dispatch runs the whole release job — a dry run proves a fix only by running it (#474)." ;;
472
+ schedule)
473
+ if [ "${RETRY_RUN:-false}" != "true" ]; then
474
+ decide true "the daily run — promotion, finalize and the npm and downloads sweeps are the colab CLI's to rule on."
475
+ elif [ "${RETRY:-}" = "true" ]; then
476
+ decide true "the hourly run re-tries the cut (the retry step above says why)."
477
+ else
478
+ decide false "the hourly run has nothing to retry, and it never promotes, finalizes or sweeps — the release job does not start."
479
+ fi ;;
480
+ workflow_run)
481
+ [ "${CONCLUSION:-}" = "success" ] \
482
+ || decide false "CI concluded \`${CONCLUSION:-unknown}\` at ${RUN_SHA:-an unnamed sha} — nothing to cut; the release job does not start."
483
+ [ -n "${RUN_SHA:-}" ] || decide true "the CI run names no sha — the release job reads main itself."
484
+ REFS="$(retry_transient git ls-remote --tags origin)" \
485
+ || decide true "could not list the tags, so a release tag at ${RUN_SHA:0:7} cannot be ruled in — the release job decides."
486
+ AT="$(awk -v s="$RUN_SHA" '$1 == s { t = substr($2, 11); if (substr(t, length(t) - 2) == "^{}") t = substr(t, 1, length(t) - 3); if (substr($2, 1, 10) == "refs/tags/" && t ~ /^v[0-9]+\.[0-9]+\.[0-9]+(-rc\.[1-9][0-9]*)?$/) { print t; exit } }' <<< "$REFS")"
487
+ [ -z "$AT" ] \
488
+ || decide false "${RUN_SHA:0:7} already carries $AT — a cut there is a no-op (#443), and a run fired by CI does nothing else; the release job does not start."
489
+ decide true "${RUN_SHA:0:7} carries no release tag — the release job decides the cut." ;;
490
+ *)
491
+ decide true "event \`${EVENT:-unknown}\` — the release job decides." ;;
492
+ esac
493
+
357
494
  release:
358
495
  name: Cut, finalize, publish
359
- # No job-level `if:` here, on purpose (#435): a red CI run is gated in the first step below,
360
- # so this run concludes success. A job-level `if:` would skip every job, GitHub would record
361
- # the whole run as `skipped` at that main sha, and `colab ship` reads any finished run that is
362
- # neither success nor cancelled as "not green". Re-run CI green on that sha and the skipped
363
- # Release (auto) row would still sit beside it, refusing every ship until main moves.
496
+ # #735: only when `decide` found work. This job-level `if:` cannot make the run conclude `skipped`
497
+ # (#435): `decide` always runs and concludes success, so a run that skips this job still concludes
498
+ # success at main's sha. A red CI run is gated in a step below as well, as before #735.
499
+ needs: decide
500
+ if: needs.decide.outputs.work == 'true'
364
501
  # EDIT: PRIVATE repo → the trunk class, [self-hosted, trunk] — a class, never a host
365
502
  # (RUNNERS, above). ubuntu-latest only on a public repo.
366
503
  runs-on: ubuntu-latest
@@ -390,12 +527,6 @@ jobs:
390
527
  # Never on workflow_run or schedule. Every write below is off when it is.
391
528
  # EDIT: if your trunk is not `main`, name it here too (the same branch as `ref:` below).
392
529
  DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && (inputs.dry_run || github.ref_name != 'main') }}
393
- # #547: 'true' on the hourly retry run. EDIT: the cron string here is byte-identical to the hourly
394
- # `cron:` under `on.schedule`.
395
- RETRY_RUN: ${{ github.event_name == 'schedule' && github.event.schedule == '47 * * * *' }}
396
- # EDIT: how recent a move of the CLI still earns a retry. Two hourly runs plus slack, so one
397
- # scheduled run GitHub drops under load does not lose the retry; a second retry is a no-op.
398
- RETRY_WINDOW_MINUTES: "130"
399
530
  steps:
400
531
  - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
401
532
  with:
@@ -421,8 +552,8 @@ jobs:
421
552
  echo
422
553
  } >> "$GITHUB_STEP_SUMMARY"
423
554
 
424
- # A red CI run on main is not a candidate. Gated here rather than by a job-level `if:` so
425
- # this run concludes success, never `skipped` (#435; the comment on the job above).
555
+ # A red CI run on main is not a candidate. The decide job already skips the release job on one
556
+ # (#735); this step keeps that true on its own, so the cut never reads a red sha whatever runs it.
426
557
  - name: Gate on the triggering CI run
427
558
  id: gate
428
559
  env:
@@ -467,39 +598,6 @@ jobs:
467
598
  git config user.name "github-actions[bot]"
468
599
  git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
469
600
 
470
- # #547: on the hourly retry run only — decide whether a cut is worth re-trying (header, "A REFUSAL
471
- # THE HANDBOOK FIXES"). Ends green either way; retry=true lets the cut step below run.
472
- - name: Retry a refused cut once the CLI moved (#547)
473
- id: retry
474
- if: env.RETRY_RUN == 'true'
475
- run: |
476
- set -uo pipefail
477
- eval "$RETRY_TRANSIENT"
478
- decide() { echo "retry=$1" >> "$GITHUB_OUTPUT"; echo "Retry run (#547): $2" | tee -a "$GITHUB_STEP_SUMMARY"; exit 0; }
479
- HEAD="$(git rev-parse HEAD)"
480
- TAGGED="$(git tag --points-at "$HEAD" --list 'v*' | head -n 1)"
481
- [ -z "$TAGGED" ] || decide false "main's head ${HEAD:0:7} already carries $TAGGED — nothing to retry."
482
- # When the CLI reached HANDBOOK_REF: a channel moves onto a release tag's commit, so that
483
- # tag's date is the move; a plain branch or an untagged commit falls back to the commit date.
484
- CLI_DIR="${COLAB%/tools/colab}"
485
- CLI_SHA="$(git -C "$CLI_DIR" rev-parse --short HEAD 2> /dev/null || echo unknown)"
486
- MOVED="$(git -C "$CLI_DIR" for-each-ref --points-at HEAD --format='%(taggerdate:unix)' refs/tags 2> /dev/null | grep -E '^[0-9]+$' | sort -n | tail -n 1)"
487
- [ -n "$MOVED" ] || MOVED="$(git -C "$CLI_DIR" log -1 --format=%ct HEAD 2> /dev/null || true)"
488
- AGE=""; [ -n "$MOVED" ] && AGE=$(( $(date +%s) - MOVED ))
489
- if [ -n "$AGE" ] && [ "$AGE" -le $(( ${RETRY_WINDOW_MINUTES:-130} * 60 )) ]; then
490
- decide true "the colab CLI ($CLI_SHA) reached HANDBOOK_REF $(( AGE / 60 )) min ago and main's head ${HEAD:0:7} has no tag — re-trying the cut with it."
491
- fi
492
- # A run this one displaced: the newest OTHER run of this workflow at main's head, cancelled.
493
- # An unreadable list re-tries rather than guessing — a cut with nothing owed is a no-op.
494
- RUNS="$(retry_transient gh run list --workflow "$GITHUB_WORKFLOW" --commit "$HEAD" --limit 20 --json databaseId,conclusion,createdAt)" \
495
- || decide true "could not list this workflow's runs at ${HEAD:0:7}, so a displaced run cannot be ruled out — re-trying the cut."
496
- LAST="$(jq -r --arg me "${GITHUB_RUN_ID:-0}" '[.[] | select((.databaseId | tostring) != $me)] | sort_by(.createdAt) | last | .conclusion // ""' <<< "$RUNS" 2> /dev/null || echo unreadable)"
497
- case "$LAST" in
498
- cancelled) decide true "the last run at main's head ${HEAD:0:7} was cancelled (displaced from the shared concurrency group) — doing its cut." ;;
499
- unreadable) decide true "could not read this workflow's runs at ${HEAD:0:7}, so a displaced run cannot be ruled out — re-trying the cut." ;;
500
- esac
501
- decide false "the colab CLI ($CLI_SHA) has not moved in the last ${RETRY_WINDOW_MINUTES:-130} min and no run at ${HEAD:0:7} was displaced — nothing to retry; the daily run cuts as usual."
502
-
503
601
  # #440: where project.yml grants `promotion: main-loop` on `deploy: tag`, promote a green dev
504
602
  # into main, then dispatch CI there — its green run fires this workflow again to cut the
505
603
  # candidate. Everywhere else the CLI answers a no-op. A refusal (dev CI not green, a push
@@ -557,7 +655,7 @@ jobs:
557
655
  # (a release.guard-run reads the working tree) and restored afterwards.
558
656
  - name: Cut a candidate (colab release cut --auto)
559
657
  id: cut
560
- if: steps.gate.outputs.cut == 'true' && (github.event_name == 'workflow_run' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule') && steps.promote.outputs.promoted != 'true' && (env.RETRY_RUN != 'true' || steps.retry.outputs.retry == 'true')
658
+ if: steps.gate.outputs.cut == 'true' && (github.event_name == 'workflow_run' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule') && steps.promote.outputs.promoted != 'true' && (env.RETRY_RUN != 'true' || needs.decide.outputs.retry == 'true')
561
659
  env:
562
660
  EVENT: ${{ github.event_name }}
563
661
  RUN_SHA: ${{ github.event.workflow_run.head_sha }}
package/tools/colab CHANGED
@@ -4371,6 +4371,80 @@ function migrationGrantRoundtripCheck(repoAbs, branch, rec) {
4371
4371
  if (!c.ok) throw new UserError(`${c.reason}; nothing was posted`);
4372
4372
  }
4373
4373
 
4374
+ // ---- #732: the grant writers judge their own poster, the way the readers judge it ----------------
4375
+ // The readers (ci-grant.js, migration-grant.js) reject a grant whose author's association is not
4376
+ // OWNER/MEMBER/COLLABORATOR (and, for a human grant under trust-humans, whose login is unlisted).
4377
+ // The writers never asked, so an account whose comments read `NONE` — while the permission API said
4378
+ // `write` — posted a grant and its label that the ship gate then refused: the hold lifted, the owner
4379
+ // thought the ship unblocked, the red row surfaced a pass later. Two layers, used by all four writers
4380
+ // (ci-grant human + reviewer, migration-grant human + reviewer) so they cannot drift:
4381
+ // 1. grantPosterPrecheck — BEFORE anything is written: predicts from a comment this account
4382
+ // already has (the association is computed per author at read time, so an old comment reads
4383
+ // exactly as the new one will). Refuses on a known-untrusted poster; nothing is posted.
4384
+ // 2. postGrantVerified — the comment FIRST, read back through the reader's own path, judged by the
4385
+ // reader's rule; the label only after it passes. A rejected comment is deleted again and the
4386
+ // label never applied — the label is what a tracker watcher reads as "unblocked", so it must
4387
+ // never flash for a grant the gate will refuse. Comment-without-label reads "not granted" to
4388
+ // every reader, so the gap between the two writes is inert.
4389
+
4390
+ /** The refusal for a poster the gate would reject — names the cause, the fix and the re-run. */
4391
+ function grantPosterRefusal(kind, p, remedy) {
4392
+ const byAssociation = !!p.association && !trustHumans.TRUSTED_ASSOCIATIONS.has(p.association);
4393
+ const fix = byAssociation || !/trust-humans/.test(p.reason)
4394
+ ? 'Post it from an account this repo lists as owner, member or collaborator — or, if this account was invited, accept the invitation first (`gh api user/repository_invitations` lists it; GitHub reports a pending invitee as NONE)'
4395
+ : 'Post it from a login listed in trunk\'s project.yml `trust-humans:`, or add this login there through a trunk change';
4396
+ return `${kind} grant not posted — the ship gate would reject it: ${p.reason}. ${fix}, then re-run: ${remedy}`;
4397
+ }
4398
+
4399
+ /**
4400
+ * Layer 1. `comments` = the issue's comments from the writer's own `ghIssueView` read (the reader's
4401
+ * path). Falls back to one page of the repo's newest comments when the account has none on this
4402
+ * issue. Throws on a known-untrusted poster; returns the context postGrantVerified needs.
4403
+ * `trust` = trunk's trust-humans for a human grant (null for a reviewer grant). A migration grant is
4404
+ * read against its merge TARGET's list (shipMigrationCtx); the writer cannot know an integration-line
4405
+ * target here, so it reads trunk's — identical for every branch cut from trunk.
4406
+ */
4407
+ function grantPosterPrecheck(repoAbs, { kind, role, comments, trust, remedy }) {
4408
+ const login = git.ghCurrentLogin();
4409
+ let p = trustHumans.posterTrust({ login, comments, trust, role });
4410
+ if (p.verdict === 'unknown' && login) {
4411
+ const recent = git.ghRecentRepoComments(repoAbs);
4412
+ if (recent) p = trustHumans.posterTrust({ login, comments: recent, trust, role });
4413
+ }
4414
+ const ctx = { kind, role, trust, login, remedy };
4415
+ if (p.verdict === 'untrusted') throw new UserError(grantPosterRefusal(kind, p, ctx.remedy));
4416
+ return ctx;
4417
+ }
4418
+
4419
+ /** Layer 2. Posts `body`, verifies its author by the reader's rule, then applies the label. */
4420
+ function postGrantVerified(repoAbs, num, body, labelArgs, poster) {
4421
+ const commentR = git.ghIssueComment(repoAbs, num, body);
4422
+ if (!commentR.ok) {
4423
+ throw new UserError(`the grant comment failed to post (${commentR.stderr.split('\n')[0] || commentR.code}) — nothing was written (the label is applied only after the comment). Re-run: ${poster.remedy}`);
4424
+ }
4425
+ const back = git.ghIssueView(repoAbs, num, ['comments']);
4426
+ const posted = back ? (back.comments || []).filter((c) => String((c && c.body) || '').trim() === body.trim()).pop() : null;
4427
+ if (!posted) {
4428
+ warn(`could not read the grant comment back from #${num} to confirm the ship gate will trust its author — check it before relying on it: colab ${poster.kind === 'CI' ? 'ci-grant' : 'migration-grant'} --list`);
4429
+ } else {
4430
+ const login = (posted.author && posted.author.login) || poster.login;
4431
+ const p = trustHumans.posterTrust({ login, comments: [posted], trust: poster.trust, role: poster.role });
4432
+ if (p.verdict !== 'trusted') {
4433
+ const why = p.verdict === 'untrusted' ? p : { ...p, reason: `${login || '(unknown)'} (no association reported) — not a repo owner/member/collaborator` };
4434
+ const del = git.ghDeleteIssueComment(repoAbs, posted.url);
4435
+ if (!del.ok) {
4436
+ throw new UserError(`${grantPosterRefusal(poster.kind, why, poster.remedy)}. The comment was posted and could NOT be deleted (${String(del.stderr || '').split('\n')[0] || del.code}); the label was not applied, so it grants nothing — delete it by hand (${posted.url || `the newest grant comment on #${num}`}): \`gh api -X DELETE repos/{owner}/{repo}/issues/comments/<id>\``);
4437
+ }
4438
+ throw new UserError(`${grantPosterRefusal(poster.kind, why, poster.remedy)}. (Its association was only readable after posting; the comment was deleted again and the label never applied.)`);
4439
+ }
4440
+ }
4441
+ const editR = git.ghIssueEdit(repoAbs, num, labelArgs);
4442
+ if (!editR.ok) {
4443
+ const del = posted ? git.ghDeleteIssueComment(repoAbs, posted.url) : { ok: false };
4444
+ throw new UserError(`the grant comment posted but the label failed (${editR.stderr.split('\n')[0] || editR.code}) — ${del.ok ? 'deleted the comment again' : `the comment stays, inert without the label${posted && posted.url ? ` (${posted.url})` : ''}`}, so this does not read as granted. Re-run: ${poster.remedy}`);
4445
+ }
4446
+ }
4447
+
4374
4448
  function cmdMigrationGrantCreate(repoAbs, num, opts) {
4375
4449
  // --branch and branch existence are already validated by cmdMigrationGrant, ahead of the
4376
4450
  // isGhUsable gate — see the comment there. Kept as a defensive re-check in case this function is
@@ -4382,7 +4456,8 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
4382
4456
  throw new UserError(`branch "${opts.branch}" does not resolve to a ref (locally or on origin) — refusing to bind a grant to a name nothing exists at`);
4383
4457
  }
4384
4458
 
4385
- const info = git.ghIssueView(repoAbs, num, opts.versionBinding ? ['state', 'labels', 'body'] : ['state', 'labels']);
4459
+ // `comments` (#732): the poster check reads this account's existing association from them.
4460
+ const info = git.ghIssueView(repoAbs, num, opts.versionBinding ? ['state', 'labels', 'body', 'comments'] : ['state', 'labels', 'comments']);
4386
4461
  if (!info) throw new UserError(`could not read #${num} from the tracker — refusing to write a grant blind`);
4387
4462
  if (info.state !== 'OPEN') {
4388
4463
  throw new UserError(`#${num} is ${info.state} — a grant expires the instant its issue closes, so granting a closed one would do nothing (CONVENTIONS.md §5, Migration exemption)`);
@@ -4402,25 +4477,26 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
4402
4477
  || `this repo has no \`${labels.MIGRATION_GRANT_LABEL}\` label`);
4403
4478
  }
4404
4479
 
4480
+ // #732: would the ship gate trust this account's grant? Refuse before writing when it is already
4481
+ // known not to — a human grant by the human readers' rule (trust-humans from trunk), a reviewer
4482
+ // grant by the bare association class its reader applies.
4483
+ const poster = grantPosterPrecheck(repoAbs, {
4484
+ kind: 'Migration', role: opts.reviewRecord ? 'reviewer' : 'human', comments: info.comments,
4485
+ trust: opts.reviewRecord ? null : trustAt(repoAbs, resolveTrunk(repoAbs, projectDoc(repoAbs))),
4486
+ remedy: opts.reviewRecord ? `the same \`colab migration-grant ${num} --branch ${opts.branch} --role ${migrationGrant.REVIEWER_ROLE} …\`` : `COLAB_HUMAN=1 colab migration-grant ${num} --branch ${opts.branch}`,
4487
+ });
4488
+
4405
4489
  // #457: a record claiming a CI round-trip pass is checked against CI BEFORE anything is written.
4406
4490
  if (opts.reviewRecord) migrationGrantRoundtripCheck(repoAbs, opts.branch, opts.reviewRecord);
4407
4491
 
4408
- const editR = git.ghIssueEdit(repoAbs, num, labels.migrationGrantLabelArgs({}));
4409
- if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
4410
-
4411
4492
  // The comment is the AUTHORITY (it carries the branch binding) — not best-effort, unlike a
4412
- // claim comment. A label with no live comment reads "granted" to a human and correctly REFUSES
4413
- // in ship, which is the worst of both: looks done, does nothing. Roll the label back rather than
4414
- // leave that state.
4493
+ // claim comment. #732: it is posted FIRST and its author verified before the label goes on, so a
4494
+ // grant the gate would refuse never shows the label (postGrantVerified).
4415
4495
  const iso = nowISO();
4416
4496
  const body = opts.reviewRecord
4417
4497
  ? migrationGrant.reviewGrantCommentBody(opts.branch, commentHost(repoAbs), iso, opts.reviewRecord)
4418
4498
  : migrationGrant.grantCommentBody(opts.branch, commentHost(repoAbs), iso);
4419
- const commentR = git.ghIssueComment(repoAbs, num, body);
4420
- if (!commentR.ok) {
4421
- git.ghIssueEdit(repoAbs, num, labels.migrationGrantLabelArgs({ clear: true }));
4422
- throw new UserError(`label applied but the grant comment failed to post (${commentR.stderr.split('\n')[0] || commentR.code}) — rolled the label back so this does not read as granted. Re-run.`);
4423
- }
4499
+ postGrantVerified(repoAbs, num, body, labels.migrationGrantLabelArgs({}), poster);
4424
4500
 
4425
4501
  if (opts.reviewRecord) {
4426
4502
  print(`Recorded a ${migrationGrant.REVIEWER_ROLE} grant on #${num} in ${shortRepo(repoAbs)} — reviewer "${opts.reviewRecord.reviewer}", branch "${opts.branch}" @ ${opts.reviewRecord.head.slice(0, 12)}.`);
@@ -4460,9 +4536,10 @@ function cmdMigrationGrantRevoke(repoAbs, num) {
4460
4536
  return 0;
4461
4537
  }
4462
4538
 
4463
- // Remove the label FIRST — the mirror image of grant's order. Grant does the weak half first
4464
- // (label) and rolls back on comment failure; revoke does the GATE-RESTORING half first, because
4465
- // the safe state to fail toward here is "already revoked," not "still granted."
4539
+ // Remove the label FIRST — the mirror image of grant's order. Grant posts the comment first and
4540
+ // applies the label only once its author is verified (#732, postGrantVerified); revoke does the
4541
+ // GATE-RESTORING half first, because the safe state to fail toward here is "already revoked,"
4542
+ // not "still granted."
4466
4543
  if (hasLabel) {
4467
4544
  const r = git.ghIssueEdit(repoAbs, num, labels.migrationGrantLabelArgs({ clear: true }));
4468
4545
  if (!r.ok) {
@@ -5250,7 +5327,8 @@ function cmdCiGrantReviewer(num, opts) {
5250
5327
  throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — a CI grant lives on the tracker, visible from any machine to the gate that reads it, and there is deliberately no local-only fallback`);
5251
5328
  }
5252
5329
 
5253
- const info = git.ghIssueView(repoAbs, num, ['state', 'labels', 'title']);
5330
+ // `comments` (#732): the poster check reads this account's existing association from them.
5331
+ const info = git.ghIssueView(repoAbs, num, ['state', 'labels', 'title', 'comments']);
5254
5332
  if (!info) throw new UserError(`could not read #${num} from the tracker — refusing to write a grant blind`);
5255
5333
  if (info.state !== 'OPEN') throw new UserError(`#${num} is ${info.state} — a grant expires the instant its issue closes`);
5256
5334
  if (!ciGrant.titleIsTrunkRed(info.title)) {
@@ -5261,6 +5339,13 @@ function cmdCiGrantReviewer(num, opts) {
5261
5339
  throw new UserError(labels.ciGrantMissingLabelHint(present) || `this repo has no \`${labels.CI_GRANT_LABEL}\` label`);
5262
5340
  }
5263
5341
 
5342
+ // #732: the reviewer reader trusts the bare association class (ci-grant.js evaluateReviewerIssue),
5343
+ // so the writer refuses an account it would reject — before any CI read, nothing written.
5344
+ const poster = grantPosterPrecheck(repoAbs, {
5345
+ kind: 'CI', role: 'reviewer', comments: info.comments, trust: null,
5346
+ remedy: `the same \`colab ci-grant ${num} --branch ${opts.branch} --role ${ciGrant.REVIEWER_ROLE} …\``,
5347
+ });
5348
+
5264
5349
  // Trunk red, in ship's sense — the identical classification cmdCiGrantCreate uses (#155).
5265
5350
  git.git(['fetch', git.remoteFor(repoAbs), trunk], repoAbs);
5266
5351
  const trunkRun = git.ghRunForSha(repoAbs, trunk);
@@ -5298,14 +5383,10 @@ function cmdCiGrantReviewer(num, opts) {
5298
5383
  const v = ciGrant.validateReviewRecord(rec);
5299
5384
  if (!v.passing) throw new UserError(`the review record is invalid: ${v.problems.join('; ')}`);
5300
5385
 
5301
- const editR = git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({}));
5302
- if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
5303
- const commentR = git.ghIssueComment(repoAbs, num,
5304
- ciGrant.reviewGrantCommentBody(opts.branch, trunk, commentHost(repoAbs), nowISO(), rec));
5305
- if (!commentR.ok) {
5306
- git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({ clear: true }));
5307
- throw new UserError(`label applied but the grant comment failed to post (${commentR.stderr.split('\n')[0] || commentR.code}) — rolled the label back so this does not read as granted. Re-run.`);
5308
- }
5386
+ // #732: comment first, its author verified, the label last (postGrantVerified).
5387
+ postGrantVerified(repoAbs, num,
5388
+ ciGrant.reviewGrantCommentBody(opts.branch, trunk, commentHost(repoAbs), nowISO(), rec),
5389
+ labels.ciGrantLabelArgs({}), poster);
5309
5390
 
5310
5391
  print(`Recorded a ${ciGrant.REVIEWER_ROLE} CI grant on #${num} in ${shortRepo(repoAbs)} — reviewer "${rec.reviewer}", branch "${opts.branch}" @ ${head.slice(0, 12)}.`);
5311
5392
  print(` Bound to that HEAD and to red ${trunk}@${shortSha(redSha)}: a new commit on either voids it. Cures: ${rec.cures}.`);
@@ -5322,7 +5403,8 @@ function cmdCiGrantCreate(repoAbs, num, opts) {
5322
5403
  throw new UserError(`branch "${opts.branch}" does not resolve to a ref (locally or on origin) — refusing to bind a grant to a name nothing exists at`);
5323
5404
  }
5324
5405
 
5325
- const info = git.ghIssueView(repoAbs, num, ['state', 'labels']);
5406
+ // `comments` (#732): the poster check reads this account's existing association from them.
5407
+ const info = git.ghIssueView(repoAbs, num, ['state', 'labels', 'comments']);
5326
5408
  if (!info) throw new UserError(`could not read #${num} from the tracker — refusing to write a grant blind`);
5327
5409
  if (info.state !== 'OPEN') {
5328
5410
  throw new UserError(`#${num} is ${info.state} — a grant expires the instant its issue closes, so granting a closed one would do nothing (CONVENTIONS.md §5, Red-trunk exemption)`);
@@ -5337,6 +5419,13 @@ function cmdCiGrantCreate(repoAbs, num, opts) {
5337
5419
  const trunk = resolveTrunk(repoAbs, doc);
5338
5420
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
5339
5421
 
5422
+ // #732: refuse before writing (and before measuring CI) when the ship gate is already known to
5423
+ // reject this account's grant — the human readers' rule, trust-humans read from trunk as ship does.
5424
+ const poster = grantPosterPrecheck(repoAbs, {
5425
+ kind: 'CI', role: 'human', comments: info.comments, trust: trustAt(repoAbs, trunk),
5426
+ remedy: `COLAB_HUMAN=1 colab ci-grant ${num} --branch ${opts.branch}`,
5427
+ });
5428
+
5340
5429
  // ---- GUARD 2 (anti-stacking) FIRST — cheaper to fail here than after measuring evidence ----
5341
5430
  git.git(['fetch', git.remoteFor(repoAbs), trunk], repoAbs);
5342
5431
  const trunkRun = git.ghRunForSha(repoAbs, trunk);
@@ -5370,16 +5459,11 @@ function cmdCiGrantCreate(repoAbs, num, opts) {
5370
5459
  }
5371
5460
  const evidenceSha = evRun.sha;
5372
5461
 
5373
- const editR = git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({}));
5374
- if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
5375
-
5462
+ // #732: comment first, its author verified, the label last (postGrantVerified).
5376
5463
  const iso = nowISO();
5377
- const commentR = git.ghIssueComment(repoAbs, num,
5378
- ciGrant.grantCommentBody(opts.branch, trunk, redSha, evidenceSha, commentHost(repoAbs), iso));
5379
- if (!commentR.ok) {
5380
- git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({ clear: true }));
5381
- throw new UserError(`label applied but the grant comment failed to post (${commentR.stderr.split('\n')[0] || commentR.code}) — rolled the label back so this does not read as granted. Re-run.`);
5382
- }
5464
+ postGrantVerified(repoAbs, num,
5465
+ ciGrant.grantCommentBody(opts.branch, trunk, redSha, evidenceSha, commentHost(repoAbs), iso),
5466
+ labels.ciGrantLabelArgs({}), poster);
5383
5467
 
5384
5468
  print(`Granted #${num} in ${shortRepo(repoAbs)} a CI exemption for branch "${opts.branch}".`);
5385
5469
  print(` Bound to red trunk sha ${shortSha(redSha)} and evidence run ${shortSha(evidenceSha)}.`);
package/tools/lib/git.js CHANGED
@@ -774,6 +774,30 @@ function ghIssueComment(repo, issueNum, body) {
774
774
  return ghApi(repo, ['-X', 'POST', `repos/{owner}/{repo}/issues/${issueNum}/comments`, '-f', `body=${body}`]);
775
775
  }
776
776
 
777
+ /**
778
+ * #732: the newest page of this repo's issue comments (REST, newest-first, up to 100) — the second
779
+ * place a grant writer looks for an existing comment by the posting account, whose
780
+ * `author_association` predicts the grant comment's (tools/lib/trust-humans.js posterTrust). Null on
781
+ * any failure: "could not read", never "no comments".
782
+ */
783
+ function ghRecentRepoComments(repo) {
784
+ const r = ghApi(repo, ['repos/{owner}/{repo}/issues/comments?sort=created&direction=desc&per_page=100']);
785
+ if (!r.ok) return null;
786
+ try { const v = JSON.parse(r.stdout); return Array.isArray(v) ? v : null; }
787
+ catch (_) { return null; }
788
+ }
789
+
790
+ /**
791
+ * #732: delete one issue comment, named by its url (`…#issuecomment-<id>`, the shape
792
+ * `gh issue view --json comments` reports) — returns {ok, stderr}. Used only to take back a grant
793
+ * comment the reader would reject; a url carrying no id is a refusal, never a guess.
794
+ */
795
+ function ghDeleteIssueComment(repo, url) {
796
+ const m = /#issuecomment-(\d+)$/.exec(String(url || ''));
797
+ if (!m) return { ok: false, code: 'no-id', stderr: `no comment id in ${JSON.stringify(url || '')}` };
798
+ return ghApi(repo, ['-X', 'DELETE', `repos/{owner}/{repo}/issues/comments/${m[1]}`]);
799
+ }
800
+
777
801
  /**
778
802
  * #357: the created-at timestamps of every `labeled` event for `label` on one issue (issue
779
803
  * events API, paginated), oldest-first — or null when the read failed. Null is "could not read",
@@ -1669,7 +1693,7 @@ module.exports = {
1669
1693
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1670
1694
  dirtyTracked, dirtyUntracked, dirtyAny,
1671
1695
  ghAvailable, ghState, ghInstalled, ghApiConditional, ghRunsAtShaRest, ghRunsAtShaUnfiltered, fullSha, ghIssueEdit, ghListLabels, ghOpenIssueNumbersByLabel, ghAssignedIssues,
1672
- ghCurrentLogin, ghIssueView, ghIssueComment, ghRunForSha, ghRunForCommit, ghRunsForCommit, ghRunsForRef, ghWorkflowStates, ghRunsAtCommit, ghRunForCommitAnyRef, commitTimeMs, ghRunsSince, summarizeRunsForCommit, isRepoOwnedRun,
1696
+ ghCurrentLogin, ghIssueView, ghIssueComment, ghRecentRepoComments, ghDeleteIssueComment, ghRunForSha, ghRunForCommit, ghRunsForCommit, ghRunsForRef, ghWorkflowStates, ghRunsAtCommit, ghRunForCommitAnyRef, commitTimeMs, ghRunsSince, summarizeRunsForCommit, isRepoOwnedRun,
1673
1697
  ghRunJobCount, ghRunJobs, ghActiveRunsOfWorkflow, ghWorkflowDispatch,
1674
1698
  ghIssueListByLabel, ghLabelDelete, ghLabelCreate, ghListLabelsDetailed, ghLabelEditDescription,
1675
1699
  ghApi, isGraphqlRateLimit, ghIssueRelease, ghClaimHolder, ghIssueLabelEvents, ghIssueLabelActors,
@@ -101,4 +101,49 @@ function labelApplierIsHuman(actors, trust, labelName) {
101
101
  return { ok: true, reason: '' };
102
102
  }
103
103
 
104
- module.exports = { KEY, LOGIN_RE, TRUSTED_ASSOCIATIONS, parseTrustHumans, authorIsHuman, labelApplierIsHuman };
104
+ /**
105
+ * The WRITER's half (#732): will a grant this account is about to post read as trusted to the
106
+ * reader above? The readers judged the author; the writers (`colab ci-grant`, `colab
107
+ * migration-grant`) never did, so an account whose comments read `NONE` posted a grant that was
108
+ * dead from the moment it landed — label applied, hold lifted, and the ship pass found the red row
109
+ * later. The repo-permission API cannot predict this (it reported `write` for exactly such an
110
+ * account), so nothing here asks it.
111
+ *
112
+ * WHY EXISTING COMMENTS PREDICT A NEW ONE. GitHub computes `authorAssociation` per author at read
113
+ * time, not per comment at write time, so every comment one author already has reads the same
114
+ * association to one reader as the grant comment will. No comment by this login anywhere the caller
115
+ * looked → `unknown`, and the caller verifies the posted comment instead.
116
+ *
117
+ * login — the posting account (`gh api user`), or null when it could not be read.
118
+ * comments — any mix of gh's shape `{ author: { login }, authorAssociation }` and the REST shape
119
+ * `{ user: { login }, author_association }`. The LAST one by `login` decides.
120
+ * trust — parseTrustHumans(...) for the human role; ignored for the reviewer role.
121
+ * role — 'human' judges by authorIsHuman (the human readers' rule); anything else judges by
122
+ * the bare association class (the reviewer readers' rule, ci-grant.js / migration-grant.js
123
+ * reviewer branch). Mirror each reader exactly: a stricter writer refuses grants the
124
+ * gate would honour, a looser one is this issue.
125
+ * Returns { verdict: 'trusted' | 'untrusted' | 'unknown', reason, association }.
126
+ */
127
+ function posterTrust({ login, comments, trust, role }) {
128
+ const me = String(login || '').toLowerCase();
129
+ const human = role === 'human';
130
+ const declared = human && trust && trust.declared;
131
+ // A declared list decides the login half with no comment at all.
132
+ if (declared && me && !(trust.humans && trust.humans.has(me))) {
133
+ return { verdict: 'untrusted', association: '',
134
+ reason: `${login} is not listed in trust-humans${trust.valid ? '' : ' (the list is malformed, so nobody is)'}` };
135
+ }
136
+ if (!me) return { verdict: 'unknown', association: '', reason: 'the posting account could not be read' };
137
+ const authorOf = (c) => String((c && ((c.author && c.author.login) || (c.user && c.user.login))) || '').toLowerCase();
138
+ const assocOf = (c) => String((c && (c.authorAssociation || c.author_association)) || '');
139
+ const mine = (Array.isArray(comments) ? comments : []).filter((c) => authorOf(c) === me && assocOf(c));
140
+ if (mine.length === 0) return { verdict: 'unknown', association: '', reason: `no comment by ${login} to read its association from` };
141
+ const association = assocOf(mine[mine.length - 1]);
142
+ const who = human
143
+ ? authorIsHuman({ login, authorAssociation: association }, trust)
144
+ : (TRUSTED_ASSOCIATIONS.has(association) ? { ok: true, reason: '' }
145
+ : { ok: false, reason: `${login} (${association}) — not a repo owner/member/collaborator` });
146
+ return who.ok ? { verdict: 'trusted', association, reason: '' } : { verdict: 'untrusted', association, reason: who.reason };
147
+ }
148
+
149
+ module.exports = { KEY, LOGIN_RE, TRUSTED_ASSOCIATIONS, parseTrustHumans, authorIsHuman, labelApplierIsHuman, posterTrust };