@futurelastic/colab-handbook 1.21.0-rc.4 → 1.21.0-rc.6

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.4"
36
+ "version": "1.21.0-rc.6"
37
37
  }
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);
@@ -5283,24 +5368,25 @@ function cmdCiGrantReviewer(num, opts) {
5283
5368
  throw new UserError(`"${opts.branch}" has no completed, successful CI run at ${shortSha(head)} (status=${evRun.status} conclusion=${evRun.conclusion || 'none'}) — a reviewer grant needs the branch green at its exact head`);
5284
5369
  }
5285
5370
 
5286
- // Every claimed cure is a red check on trunk at the red sha.
5287
- const redRunJobs = trunkRedRunJobs(repoAbs, trunk, redSha);
5288
- const redJobs = redRunJobs === null ? null : ciCure.redJobSet(redRunJobs);
5371
+ // Every claimed cure is a red check on trunk at the red sha — the reviewer's red set (#730), which
5372
+ // also names the jobs of a cancelled run whose re-run is spent; each such cure is then proven on the
5373
+ // branch's own run of the same workflow and job at the head.
5374
+ const redJobs = trunkReviewerRedJobs(repoAbs, trunk, redSha);
5289
5375
  const cr = ciGrant.curesAreRed(ciGrant.parseCures(rec.cures), redJobs);
5290
5376
  if (!cr.ok) throw new UserError(`${cr.reason}; nothing was posted`);
5377
+ const proof = ciGrant.spentCancelledCuresProven(cr.matched, () => branchHeadJobs(repoAbs, opts.branch, head));
5378
+ if (!proof.ok) {
5379
+ throw new UserError(`${proof.reason}; nothing was posted. Re-run once that workflow has succeeded on the branch head, or a human grants it: \`COLAB_HUMAN=1 colab ci-grant ${num} --branch ${opts.branch}\``);
5380
+ }
5291
5381
 
5292
5382
  rec.red = redSha.toLowerCase();
5293
5383
  const v = ciGrant.validateReviewRecord(rec);
5294
5384
  if (!v.passing) throw new UserError(`the review record is invalid: ${v.problems.join('; ')}`);
5295
5385
 
5296
- const editR = git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({}));
5297
- if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
5298
- const commentR = git.ghIssueComment(repoAbs, num,
5299
- ciGrant.reviewGrantCommentBody(opts.branch, trunk, commentHost(repoAbs), nowISO(), rec));
5300
- if (!commentR.ok) {
5301
- git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({ clear: true }));
5302
- 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.`);
5303
- }
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);
5304
5390
 
5305
5391
  print(`Recorded a ${ciGrant.REVIEWER_ROLE} CI grant on #${num} in ${shortRepo(repoAbs)} — reviewer "${rec.reviewer}", branch "${opts.branch}" @ ${head.slice(0, 12)}.`);
5306
5392
  print(` Bound to that HEAD and to red ${trunk}@${shortSha(redSha)}: a new commit on either voids it. Cures: ${rec.cures}.`);
@@ -5317,7 +5403,8 @@ function cmdCiGrantCreate(repoAbs, num, opts) {
5317
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`);
5318
5404
  }
5319
5405
 
5320
- 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']);
5321
5408
  if (!info) throw new UserError(`could not read #${num} from the tracker — refusing to write a grant blind`);
5322
5409
  if (info.state !== 'OPEN') {
5323
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)`);
@@ -5332,6 +5419,13 @@ function cmdCiGrantCreate(repoAbs, num, opts) {
5332
5419
  const trunk = resolveTrunk(repoAbs, doc);
5333
5420
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
5334
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
+
5335
5429
  // ---- GUARD 2 (anti-stacking) FIRST — cheaper to fail here than after measuring evidence ----
5336
5430
  git.git(['fetch', git.remoteFor(repoAbs), trunk], repoAbs);
5337
5431
  const trunkRun = git.ghRunForSha(repoAbs, trunk);
@@ -5365,16 +5459,11 @@ function cmdCiGrantCreate(repoAbs, num, opts) {
5365
5459
  }
5366
5460
  const evidenceSha = evRun.sha;
5367
5461
 
5368
- const editR = git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({}));
5369
- if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
5370
-
5462
+ // #732: comment first, its author verified, the label last (postGrantVerified).
5371
5463
  const iso = nowISO();
5372
- const commentR = git.ghIssueComment(repoAbs, num,
5373
- ciGrant.grantCommentBody(opts.branch, trunk, redSha, evidenceSha, commentHost(repoAbs), iso));
5374
- if (!commentR.ok) {
5375
- git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({ clear: true }));
5376
- 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.`);
5377
- }
5464
+ postGrantVerified(repoAbs, num,
5465
+ ciGrant.grantCommentBody(opts.branch, trunk, redSha, evidenceSha, commentHost(repoAbs), iso),
5466
+ labels.ciGrantLabelArgs({}), poster);
5378
5467
 
5379
5468
  print(`Granted #${num} in ${shortRepo(repoAbs)} a CI exemption for branch "${opts.branch}".`);
5380
5469
  print(` Bound to red trunk sha ${shortSha(redSha)} and evidence run ${shortSha(evidenceSha)}.`);
@@ -12795,10 +12884,10 @@ function shipCiGrants(repoAbs, gh, issues, branch, trunk, redSha) {
12795
12884
  // host's revoke window, and trunk's red checks at redSha, read lazily and at most once.
12796
12885
  policy: ciGrant.parseGrantPolicy(projectDocAt(repoAbs, trunk)).policy,
12797
12886
  now: Date.now(),
12798
- redJobs: () => {
12799
- const jobs = trunkRedRunJobs(repoAbs, trunk, redSha);
12800
- return jobs === null ? null : ciCure.redJobSet(jobs);
12801
- },
12887
+ // #730: the reviewer's red set (spent cancelled runs included), and the branch head's jobs that
12888
+ // prove a spent cancelled cure — the same two reads `colab ci-grant --role ci-reviewer` mints on.
12889
+ redJobs: () => trunkReviewerRedJobs(repoAbs, trunk, redSha),
12890
+ branchJobs: () => (evRun && evRun.sha ? branchHeadJobs(repoAbs, branch, evRun.sha) : null),
12802
12891
  });
12803
12892
  }
12804
12893
 
@@ -12992,6 +13081,49 @@ function trunkRedRunJobs(repoAbs, trunk, sha, limit) {
12992
13081
  return out;
12993
13082
  }
12994
13083
 
13084
+ /**
13085
+ * #730 — the red-job set the REVIEWER grant reads at `sha` (mint and ship; the cure rule keeps
13086
+ * `trunkRedRunJobs` + `redJobSet`). Same run read as `trunkRedRunJobs`, plus the jobs of every
13087
+ * cancelled run whose one re-run is spent (ci-cure.js `spentCancelledRuns`), shaped by the pure
13088
+ * `reviewerRedJobSet`. `null` on any failed read, or when nothing red can be named.
13089
+ */
13090
+ function trunkReviewerRedJobs(repoAbs, trunk, sha) {
13091
+ const runsAll = git.ghRunsForCommit(repoAbs, trunk, sha);
13092
+ const runs = runsAll === null ? null : runsAll.filter(git.isRepoOwnedRun);
13093
+ if (runs === null || runs.length === 0) return null;
13094
+ const failedRuns = runs.filter((r) => r.status === 'completed' && r.conclusion !== 'success' && r.conclusion !== 'cancelled');
13095
+ const jobsOf = (list) => {
13096
+ const out = [];
13097
+ for (const r of list) {
13098
+ const jobs = git.ghRunJobs(repoAbs, r.databaseId);
13099
+ if (jobs === null) return null;
13100
+ out.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '', workflowId: r.workflowId ?? null })));
13101
+ }
13102
+ return out;
13103
+ };
13104
+ const failedRunJobs = jobsOf(failedRuns);
13105
+ const cancelledRunJobs = jobsOf(ciCure.spentCancelledRuns(runs));
13106
+ if (failedRunJobs === null || cancelledRunJobs === null) return null;
13107
+ return ciCure.reviewerRedJobSet({ failedRunJobs, cancelledRunJobs });
13108
+ }
13109
+
13110
+ /**
13111
+ * #730 — every job of every run on `branch` at `sha`, tagged with its run's `workflowName`,
13112
+ * `runStatus` and `runConclusion`: what ci-grant.js `spentCancelledCuresProven` reads. `null` on
13113
+ * any failed read — never an empty set standing for "could not tell".
13114
+ */
13115
+ function branchHeadJobs(repoAbs, branch, sha) {
13116
+ const runs = git.ghRunsForCommit(repoAbs, branch, sha);
13117
+ if (runs === null) return null;
13118
+ const out = [];
13119
+ for (const r of runs.filter(git.isRepoOwnedRun)) {
13120
+ const jobs = git.ghRunJobs(repoAbs, r.databaseId);
13121
+ if (jobs === null) return null;
13122
+ out.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '', runStatus: r.status || null, runConclusion: r.conclusion || null })));
13123
+ }
13124
+ return out;
13125
+ }
13126
+
12995
13127
  /**
12996
13128
  * The red-job set at the red sha the prior exemption on this continuous red was measured against
12997
13129
  * (#477) — read only when condition 3 refused as stacked AND job evidence exists (containment + 2a
@@ -800,6 +800,52 @@ function redJobSet(redRunJobs) {
800
800
  return shaped.redJobs.map((j) => ({ name: j.name, workflowName: j.workflowName }));
801
801
  }
802
802
 
803
+ /** Run conclusions that executed nothing — a run of a workflow carrying only these never finished. */
804
+ const NEUTRAL_RUN_CONCLUSIONS = new Set(['cancelled', 'skipped']);
805
+
806
+ /**
807
+ * #730 — the runs at one trunk sha that make it red by being cancelled with their one keyed re-run
808
+ * already spent (#628 asks for exactly one re-run): a NAMED, completed, `cancelled` run whose
809
+ * `attempt` is greater than 1, in a workflow with no other run at the sha that ran (anything but
810
+ * `cancelled`/`skipped` — such a run supersedes it, #92). An unknown `attempt` is not a spent one:
811
+ * the re-run is still the next step, so the run stays out. PURE; `runs` are run rows (repo-owned).
812
+ */
813
+ function spentCancelledRuns(runs) {
814
+ if (!Array.isArray(runs)) return [];
815
+ const ran = new Set(runs.filter((r) => r && r.workflowName && !NEUTRAL_RUN_CONCLUSIONS.has(r.conclusion)).map((r) => r.workflowName));
816
+ return runs.filter((r) => r && r.workflowName && r.status === 'completed' && r.conclusion === 'cancelled'
817
+ && Number(r.attempt) > 1 && !ran.has(r.workflowName));
818
+ }
819
+
820
+ /**
821
+ * #730 — the red-job set the REVIEWER grant reads (mint and ship), never the cure rule's: the cure
822
+ * path's `redJobSet` over the failed runs, plus every job of a spent cancelled run
823
+ * (`spentCancelledRuns`) that did not pass or skip. Those carry `spentCancelled: true`, which makes the
824
+ * grant prove each such cure on the branch's own run of the same workflow and job
825
+ * (ci-grant.js `spentCancelledCuresProven`) — a cancelled check verified nothing on either side, so
826
+ * the branch's run must have.
827
+ *
828
+ * `failedRunJobs` / `cancelledRunJobs` are the raw job rows (tagged `workflowName`) of each kind of
829
+ * run. `null` when either is not an array or any job is unfinished (unmeasurable), and when both sets
830
+ * are empty — the same "nothing red could be named" answer the cure path gives. PURE.
831
+ */
832
+ function reviewerRedJobSet({ failedRunJobs, cancelledRunJobs } = {}) {
833
+ if (!Array.isArray(failedRunJobs) || !Array.isArray(cancelledRunJobs)) return null;
834
+ const failed = failedRunJobs.length ? redJobSet(failedRunJobs) : [];
835
+ if (failed === null) return null;
836
+ if (cancelledRunJobs.some((j) => !j || j.status !== 'completed')) return null;
837
+ const out = [...failed];
838
+ const seen = new Set(out.map(jobKey));
839
+ for (const j of cancelledRunJobs) {
840
+ if (j.conclusion === 'success' || j.conclusion === 'skipped') continue;
841
+ const red = { name: j.name, workflowName: j.workflowName || '', spentCancelled: true };
842
+ if (seen.has(jobKey(red))) continue;
843
+ seen.add(jobKey(red));
844
+ out.push(red);
845
+ }
846
+ return out.length ? out : null;
847
+ }
848
+
803
849
  /**
804
850
  * Progress past condition 3 (#477) — PURE. `prior` is the red-job set at the red sha the most recent
805
851
  * exemption on this continuous red was measured against; `current` the red-job set at trunk's red
@@ -1051,5 +1097,5 @@ function admittedText(admitted) {
1051
1097
 
1052
1098
  module.exports = { cureVerdict, redJobsProvenOnBranch, workflowCarveOut, manifestStepProof, shapeJobEvidence, dryRunDispatchPlan,
1053
1099
  cureDispatchPlan, dispatchEvidence,
1054
- priorRedShaFromMessage, redJobSet, redSetShrank,
1100
+ priorRedShaFromMessage, redJobSet, redSetShrank, spentCancelledRuns, reviewerRedJobSet,
1055
1101
  WORKFLOW_REFUSAL, MANIFEST_SCRIPTS_REFUSAL, PYTHON_MANIFEST_REFUSAL, PUBLISH_STEP_MARKER, DRY_RUN_STEP, DRY_RUN_CONDITIONAL_STEPS };
@@ -259,10 +259,10 @@ function syncedFrom(opts, headSha, redSha, evidenceSha) {
259
259
  * `records` maps issue number → the `ghIssueView` result for that issue, or `null` on a failed
260
260
  * read (the caller's job, not this function's).
261
261
  *
262
- * `opts` (#504) additionally carries `{ policy, now, redJobs }` for the reviewer role: per issue a
263
- * live human grant wins, unchanged; otherwise an issue carrying a live reviewer grant is judged by
264
- * evaluateReviewerIssue (records must then include `title`). `redJobs` is a thunk, called at most
265
- * once per set. A granted reviewer entry carries `role: 'ci-reviewer'`, `reviewer`, `head`, `cures`.
262
+ * `opts` (#504) additionally carries `{ policy, now, redJobs, branchJobs }` for the reviewer role: per
263
+ * issue a live human grant wins, unchanged; otherwise an issue carrying a live reviewer grant is
264
+ * judged by evaluateReviewerIssue (records must then include `title`). `redJobs` and `branchJobs`
265
+ * (#730) are thunks, each called at most once per set. A granted reviewer entry carries `role: 'ci-reviewer'`, `reviewer`, `head`, `cures`.
266
266
  */
267
267
  function evaluateShipSet(issues, records, branch, trunk, redTrunkSha, evidence, labelName, opts) {
268
268
  const list = Array.isArray(issues) ? issues : [];
@@ -281,6 +281,14 @@ function evaluateShipSet(issues, records, branch, trunk, redTrunkSha, evidence,
281
281
  }
282
282
  return redJobsMemo;
283
283
  };
284
+ // #730: the branch head's jobs, read only when a cure names a spent cancelled check.
285
+ let branchJobsMemo;
286
+ const branchJobs = () => {
287
+ if (branchJobsMemo === undefined) {
288
+ try { branchJobsMemo = opts && typeof opts.branchJobs === 'function' ? opts.branchJobs() : null; } catch (_) { branchJobsMemo = null; }
289
+ }
290
+ return branchJobsMemo;
291
+ };
284
292
  for (const n of list) {
285
293
  const rec = records ? records[n] : null;
286
294
  const v = evaluateIssue(rec, branch, trunk, redTrunkSha, evidence, n, labelName, opts);
@@ -294,7 +302,7 @@ function evaluateShipSet(issues, records, branch, trunk, redTrunkSha, evidence,
294
302
  const hasReviewer = !!rec && liveGrantRecords(rec.comments).some((g) => g.role !== 'human');
295
303
  if (!hasReviewer) { missing.push({ issue: n, reason: v.reason }); continue; }
296
304
  const r = evaluateReviewerIssue(rec, { branch, trunk, redTrunkSha, evidence, issueNum: n, labelName,
297
- policy: opts && opts.policy, now: opts && opts.now, redJobs });
305
+ policy: opts && opts.policy, now: opts && opts.now, redJobs, branchJobs });
298
306
  if (r.ok) {
299
307
  granted.push({ issue: n, role: REVIEWER_ROLE, reviewer: r.grant.reviewer, head: r.grant.head,
300
308
  branch: r.grant.branch, by: r.grant.login, at: r.grant.at, redSha: r.grant.redSha, evidenceSha: r.grant.head,
@@ -535,7 +543,40 @@ function curesAreRed(cures, redJobs) {
535
543
  return { ok: false, unmatched,
536
544
  reason: `the review claims to cure ${unmatched.map((c) => `\`${c}\``).join(', ')}, which ${unmatched.length === 1 ? 'is' : 'are'} not red on trunk at that sha (red: ${red})` };
537
545
  }
538
- return { ok: true, unmatched: [], reason: '' };
546
+ // #730: the red job each cure names, so a caller can prove the spent-cancelled ones on the branch.
547
+ const matched = list.map((c) => redJobs.find((j) => checkLabel(j) === c) || redJobs.find((j) => j.name === c));
548
+ return { ok: true, unmatched: [], matched, reason: '' };
549
+ }
550
+
551
+ /**
552
+ * #730 — a cure naming a spent cancelled check (ci-cure.js `reviewerRedJobSet`, `spentCancelled`)
553
+ * is proven only by the branch's OWN run of that workflow: a completed `success` run whose job of the
554
+ * same name concluded `success` too. "The branch's CI is green" is not enough here — the trunk check
555
+ * verified nothing, so a branch run of it that was itself cancelled or skipped proves nothing either,
556
+ * and a green sibling workflow must never stand in for it.
557
+ *
558
+ * `matched` is curesAreRed's `matched`; `branchJobs` is every job at the branch head, each tagged with
559
+ * its run's `workflowName`, `runStatus` and `runConclusion` — or null when it could not be read.
560
+ * Returns `{ ok, reason }`; ok without reading anything when no cure names a spent cancelled check.
561
+ */
562
+ function spentCancelledCuresProven(matched, branchJobs) {
563
+ const wanted = (Array.isArray(matched) ? matched : []).filter((j) => j && j.spentCancelled);
564
+ if (wanted.length === 0) return { ok: true, reason: '' };
565
+ const rows = typeof branchJobs === 'function' ? branchJobs() : branchJobs;
566
+ if (!Array.isArray(rows)) {
567
+ return { ok: false, reason: `the branch head's jobs could not be read — ${wanted.map((j) => `\`${checkLabel(j)}\``).join(', ')} never finished on trunk, so only the branch's own run of it can prove the cure, and an unread run proves nothing` };
568
+ }
569
+ const unproven = wanted.filter((red) => !rows.some((b) => b && (b.workflowName || '') === (red.workflowName || '') && b.name === red.name
570
+ && b.runStatus === 'completed' && b.runConclusion === 'success' && b.status === 'completed' && b.conclusion === 'success'));
571
+ if (unproven.length) {
572
+ const seen = (red) => {
573
+ const same = rows.filter((b) => b && (b.workflowName || '') === (red.workflowName || '') && b.name === red.name);
574
+ return same.length ? same.map((b) => `run ${b.runConclusion || b.runStatus || '?'} / job ${b.conclusion || b.status || '?'}`).join(', ') : 'no such job at the head';
575
+ };
576
+ return { ok: false,
577
+ reason: `${unproven.map((j) => `\`${checkLabel(j)}\` (${seen(j)})`).join(', ')} never finished on trunk (its re-run was spent cancelled), and the branch's own run of it did not succeed at its head — a cancelled or skipped run proves nothing, on either side` };
578
+ }
579
+ return { ok: true, reason: '' };
539
580
  }
540
581
 
541
582
  function titleIsTrunkRed(title) {
@@ -544,10 +585,12 @@ function titleIsTrunkRed(title) {
544
585
 
545
586
  /**
546
587
  * The reviewer-grant verdict for one issue on a ship. `ctx` = { branch, trunk, redTrunkSha, evidence,
547
- * issueNum, labelName, policy, now, redJobs } where `evidence` is `{ok, sha}` for the branch's CURRENT
548
- * remote head (or null on a failed read), `now` is an ISO instant or ms (absent = Date.now()), and
549
- * `redJobs` is a function returning the red-job set at `redTrunkSha` (or null) — called only once
550
- * everything cheaper has passed. Checks, cheapest first, each with its own reason. `record` must be a
588
+ * issueNum, labelName, policy, now, redJobs, branchJobs } where `evidence` is `{ok, sha}` for the
589
+ * branch's CURRENT remote head (or null on a failed read), `now` is an ISO instant or ms (absent =
590
+ * Date.now()), `redJobs` is a function returning the red-job set at `redTrunkSha` (or null) — called
591
+ * only once everything cheaper has passed — and `branchJobs` (#730) a function returning the branch
592
+ * head's jobs for `spentCancelledCuresProven`, called only when a cure names a spent cancelled
593
+ * check (absent reads as unmeasured, which refuses such a cure). Checks, cheapest first, each with its own reason. `record` must be a
551
594
  * ghIssueView result carrying `title`. Returns { ok, grant, reason }.
552
595
  */
553
596
  function evaluateReviewerIssue(record, ctx) {
@@ -588,6 +631,13 @@ function evaluateReviewerIssue(record, ctx) {
588
631
  try { redJobs = typeof c.redJobs === 'function' ? c.redJobs() : (c.redJobs === undefined ? null : c.redJobs); } catch (_) { redJobs = null; }
589
632
  const cr = curesAreRed(parseCures(g.record.cures), redJobs);
590
633
  if (!cr.ok) return no(`#${issue}: ${cr.reason}`, g);
634
+ // #730: a spent cancelled cure must still be proven on the branch's own run, at ship as at mint.
635
+ let branchJobs = null;
636
+ const pr = spentCancelledCuresProven(cr.matched, () => {
637
+ try { branchJobs = typeof c.branchJobs === 'function' ? c.branchJobs() : (c.branchJobs === undefined ? null : c.branchJobs); } catch (_) { branchJobs = null; }
638
+ return branchJobs;
639
+ });
640
+ if (!pr.ok) return no(`#${issue}: ${pr.reason}`, g);
591
641
  return { issue, ok: true, grant: g, reason: '' };
592
642
  }
593
643
 
@@ -599,5 +649,5 @@ module.exports = {
599
649
  // #504 — the reviewer role
600
650
  REVIEW_GRANT_MARK, REVIEW_GRANT_RE, REVIEWER_ROLE, GRANT_ROLES, REVIEW_RECORD_FIELDS, TRUNK_RED_TITLE_PREFIX,
601
651
  GRANT_POLICIES, parseGrantPolicy, parseCures, formatCures, validateReviewRecord, reviewGrantCommentBody,
602
- parseReviewGrant, liveGrantRecords, checkLabel, curesAreRed, titleIsTrunkRed, evaluateReviewerIssue,
652
+ parseReviewGrant, liveGrantRecords, checkLabel, curesAreRed, spentCancelledCuresProven, titleIsTrunkRed, evaluateReviewerIssue,
603
653
  };
@@ -108,6 +108,8 @@ function restRow(x) {
108
108
  // #705: the ref the run is on — a zero-jobs run is told apart from one queued behind its own
109
109
  // concurrency group by an older in-progress run of the same workflow on the SAME ref.
110
110
  headBranch: x.head_branch || null,
111
+ // #730: which attempt the row is — a re-run keeps the run id and bumps this.
112
+ attempt: x.run_attempt ?? null,
111
113
  };
112
114
  }
113
115
 
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",
@@ -1015,7 +1039,9 @@ function ghRunsForCommit(repo, branch, sha, limit = 10) {
1015
1039
  // id, never its display name; mapped to `workflowId`, the name the REST row (ci-wait restRow) uses.
1016
1040
  // updatedAt is additive (#555): a finished run's completion time, the lone-member wait's anchor.
1017
1041
  // headBranch is additive (#705): the ref the concurrency-queue read (ghActiveRunsOfWorkflow) keys on.
1018
- '--json', 'headSha,status,conclusion,createdAt,updatedAt,databaseId,workflowName,workflowDatabaseId,event,headBranch'], { cwd: repo });
1042
+ // attempt is additive (#730): a cancelled run whose one re-run is spent (attempt > 1) is red to the
1043
+ // reviewer grant (ci-cure.js spentCancelledRuns); the REST row carries it as run_attempt.
1044
+ '--json', 'headSha,status,conclusion,createdAt,updatedAt,databaseId,workflowName,workflowDatabaseId,event,headBranch,attempt'], { cwd: repo });
1019
1045
  if (!r.ok) return null;
1020
1046
  let runs;
1021
1047
  try { runs = JSON.parse(r.stdout); } catch (_) { return null; }
@@ -1667,7 +1693,7 @@ module.exports = {
1667
1693
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1668
1694
  dirtyTracked, dirtyUntracked, dirtyAny,
1669
1695
  ghAvailable, ghState, ghInstalled, ghApiConditional, ghRunsAtShaRest, ghRunsAtShaUnfiltered, fullSha, ghIssueEdit, ghListLabels, ghOpenIssueNumbersByLabel, ghAssignedIssues,
1670
- 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,
1671
1697
  ghRunJobCount, ghRunJobs, ghActiveRunsOfWorkflow, ghWorkflowDispatch,
1672
1698
  ghIssueListByLabel, ghLabelDelete, ghLabelCreate, ghListLabelsDetailed, ghLabelEditDescription,
1673
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 };