@futurelastic/colab-handbook 0.0.0-bootstrap.0 → 1.12.0-rc.9

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.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +310 -3
  3. package/README.vi.md +280 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +137 -0
  22. package/templates/release-auto.yml +475 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13785 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +259 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify.js +188 -0
  63. package/tools/lib/npm-publish-guard.js +242 -0
  64. package/tools/lib/orphan-worktree.js +127 -0
  65. package/tools/lib/owner-branch.js +182 -0
  66. package/tools/lib/place.js +782 -0
  67. package/tools/lib/ports.js +167 -0
  68. package/tools/lib/procs.js +185 -0
  69. package/tools/lib/readiness.js +240 -0
  70. package/tools/lib/records.js +185 -0
  71. package/tools/lib/refs-brake.js +95 -0
  72. package/tools/lib/release-channel.js +99 -0
  73. package/tools/lib/release-cut.js +822 -0
  74. package/tools/lib/release-finalize.js +481 -0
  75. package/tools/lib/release-policy.js +358 -0
  76. package/tools/lib/release-tag.js +225 -0
  77. package/tools/lib/ship-batch.js +277 -0
  78. package/tools/lib/ship-roles.js +71 -0
  79. package/tools/lib/ship-target-sync.js +181 -0
  80. package/tools/lib/shipguard.js +317 -0
  81. package/tools/lib/shipped-branch.js +56 -0
  82. package/tools/lib/solo.js +213 -0
  83. package/tools/lib/squash.js +515 -0
  84. package/tools/lib/stale-base.js +70 -0
  85. package/tools/lib/stamp.js +740 -0
  86. package/tools/lib/state.js +262 -0
  87. package/tools/lib/teardown.js +83 -0
  88. package/tools/lib/trust-humans.js +104 -0
  89. package/tools/lib/util.js +98 -0
  90. package/tools/lib/wake.js +188 -0
  91. package/tools/lib/workflow-triggers.js +273 -0
  92. package/tools/lib/writes-authority.js +237 -0
  93. package/tools/lib/yaml.js +101 -0
  94. package/bin/cli.js +0 -3
@@ -0,0 +1,307 @@
1
+ 'use strict';
2
+ /**
3
+ * The ci-grant marker (#105) — a per-issue, human-only, branch-bound, RED-TRUNK-SHA-bound,
4
+ * expiring exemption to `colab ship`'s trunk-CI-green precondition (`shipCiCheck` in tools/colab).
5
+ *
6
+ * WHY A GRANT EXISTS AT ALL. `ship`'s first precondition — a completed, successful CI run for the
7
+ * target's head sha — is right by default: unattended merges into a red trunk are exactly how a
8
+ * broken repo stays broken. But it has exactly one un-exitable case: a GENUINELY red trunk, where
9
+ * the candidate branch's entire content IS the fix. Nothing inside the merge can clear the
10
+ * precondition, and nothing outside it can either — the fix cannot reach trunk without shipping,
11
+ * and shipping requires the green the fix would produce. Without a sanctioned door the repo is
12
+ * bricked for unattended work until a human performs the whole of Phase B by hand — squash
13
+ * trailers, guard push, teardown, evidence, claim release, group-label cleanup — precisely the
14
+ * surface the gates exist to get right, and the hand path is where their mistakes come back (a
15
+ * wrong `Closes #N` is immutable once pushed).
16
+ *
17
+ * THIS IS NOT THE SAME DEADLOCK AS THE ONE CONVENTIONS.md:505 ALREADY NAMES. That text (and the
18
+ * "ask by sha, not by recency" fix) resolves a FALSE red — a cancelled `cancel-in-progress`
19
+ * straggler outranking a passing run on the same commit. Asking per-sha fixed a red that was never
20
+ * real. A genuinely red trunk is untreated by that fix: the sha really did fail, and no amount of
21
+ * asking differently changes the answer.
22
+ *
23
+ * MODELLED ON tools/lib/migration-grant.js (#98) — same problem SHAPE (a precondition right in
24
+ * general, wrong for exactly one legitimate deliverable), so it gets the same solution rather than
25
+ * a new mechanism: two markers (a LABEL gating who may even attempt the read, a COMMENT carrying
26
+ * what the label cannot), written under `COLAB_HUMAN=1`, read on `ship`, visible from any machine.
27
+ * DELIBERATELY A SEPARATE MODULE, not a shared base extracted from migration-grant.js — extracting
28
+ * would touch a passing safety-critical module for a reason unrelated to migrations, the same
29
+ * argument tools/lib/ship-migration-grant.test.js makes about its own fixture.
30
+ *
31
+ * WHY THIS GRANT IS STRICTLY MORE DANGEROUS THAN THE MIGRATION ONE, and what compensates:
32
+ * - A bad migration grant merges ONE reviewed schema change. A bad CI grant merges into a repo
33
+ * whose OWN TEST SUITE is known-failing — the merge itself is unverified by the gate that
34
+ * exists to verify it.
35
+ * - So, unlike migration-grant, THIS grant is bound to the RED TRUNK SHA it was reviewed
36
+ * against, and expires the instant trunk's head moves — granted-and-consumed or not. A grant
37
+ * surviving into a DIFFERENT red (trunk moved, a new and different failure) was never reviewed
38
+ * against that failure and must not silently keep working.
39
+ * - And it requires MEASURED evidence — a real, completed, successful CI run on the branch's OWN
40
+ * head — never a human's say-so alone. `--evidence-run` (tools/colab) is a recording-only
41
+ * pointer for the audit trail; it can never substitute for the measured run this module checks.
42
+ * - Anti-stacking (evaluated at grant-CREATE time in tools/colab, not here — this module is pure)
43
+ * refuses a second grant while trunk is STILL red after one grant already merged something:
44
+ * otherwise the exemption becomes the way work ships on a permanently broken repo, exactly the
45
+ * failure the gate was built to prevent.
46
+ *
47
+ * TWO MARKERS, TWO DIFFERENT JOBS — read together, never one alone, same split as migration-grant:
48
+ * - a LABEL (`ci-granted`, tools/lib/labels.js) — a cheap `gh issue list --label` query, and the
49
+ * load-bearing half: applying a label on GitHub requires triage/write permission, so a
50
+ * drive-by commenter on a public repo cannot manufacture a grant merely by posting a
51
+ * well-formed comment.
52
+ * - a COMMENT (this module's GRANT_MARK/REVOKE_MARK) — carries what a label cannot: the branch,
53
+ * the RED TRUNK SHA, the EVIDENCE RUN SHA, who granted it, and when.
54
+ *
55
+ * Both are required for a grant to read as live (evaluateIssue, below) — a label with no live
56
+ * comment is exactly the state a rolled-back/failed write leaves, and must refuse, not "grant".
57
+ *
58
+ * PURE BY CONSTRUCTION, same posture as migration-grant.js / readiness.js / landed.js /
59
+ * shipguard.js: signals in, verdict out. No git, no network, no `gh`. The caller (tools/colab)
60
+ * measures the red trunk sha and the branch's evidence run and hands them in — this module never
61
+ * reads either off the network itself, so every decision worth pinning lives where `node --test`
62
+ * can reach it directly.
63
+ *
64
+ * WHO IS ALLOWED TO WRITE THE COMMENT is a DIFFERENT question from who is allowed to APPLY the
65
+ * label — identical split to migration-grant.js. This module answers only the READ side
66
+ * (TRUSTED_ASSOCIATIONS), closing the "drive-by comment on a public repo" hole the label narrows
67
+ * but does not by itself close. The human-only WRITE path is enforced in tools/colab via
68
+ * `COLAB_HUMAN=1`, the same bar `cmdPromote` and `cmdMigrationGrant` already hold.
69
+ */
70
+
71
+ /** The two comment markers. STABLE WIRE FORMAT — do not reword casually; `tools/colab` and any
72
+ * vendored reader parse these verbatim. Deliberately a DIFFERENT leading emoji from BOTH
73
+ * migration-grant's marks (🛢/🚫) AND each other, so no regex here or in migration-grant.js can
74
+ * ever cross-match — a four-way collision test in ci-grant.test.js pins this. */
75
+ const GRANT_MARK = '🚨 Red-trunk CI grant';
76
+ const REVOKE_MARK = '🧯 Red-trunk CI grant revoked';
77
+
78
+ const GRANT_RE = /^🚨 Red-trunk CI grant — branch `([^`]*)` · red `([^`]*)`@`([^`]*)` · evidence `([^`]*)` · host `([^`]*)` · (\S+)/;
79
+ const REVOKE_RE = /^🧯 Red-trunk CI grant revoked — branch `([^`]*)` · host `([^`]*)` · (\S+)/;
80
+
81
+ /** The exact grant-comment body. Keep in lockstep with GRANT_RE. Carries strictly more than
82
+ * migration-grant's equivalent: the TRUNK NAME + RED SHA it was reviewed against, and the
83
+ * EVIDENCE RUN sha that proved the branch's own head green — both are read back and re-checked
84
+ * by evaluateIssue, not merely stored for audit. */
85
+ function grantCommentBody(branch, trunk, redSha, evidenceSha, host, iso) {
86
+ return `${GRANT_MARK} — branch \`${branch}\` · red \`${trunk}\`@\`${redSha}\` · evidence \`${evidenceSha}\` · host \`${host}\` · ${iso}`
87
+ + ` — this exempts THIS BRANCH from the trunk-CI-green precondition ONLY, only while \`${trunk}\``
88
+ + ` is still at \`${redSha}\`, and expires when this issue closes.`;
89
+ }
90
+
91
+ /** The exact revoke-comment body. Keep in lockstep with REVOKE_RE. `branch` is the branch named in
92
+ * the record for the audit trail — revocation itself is NOT branch-scoped (see evaluateIssue doc
93
+ * in migration-grant.js; identical reasoning applies here). */
94
+ function revokeCommentBody(branch, host, iso) {
95
+ return `${REVOKE_MARK} — branch \`${branch}\` · host \`${host}\` · ${iso}`
96
+ + ' — every grant on this issue up to this point is cancelled.';
97
+ }
98
+
99
+ /**
100
+ * Every GRANT_MARK comment not cancelled by a LATER REVOKE_MARK — identical algorithm to
101
+ * migration-grant.js's liveGrants (see that module's doc for why revocation is NOT author-scoped).
102
+ * Sort is by `createdAt` (GitHub's own timestamp, authoritative — never comment array order).
103
+ *
104
+ * Returns [{branch, trunk, redSha, evidenceSha, host, at, login, authorAssociation}], oldest-first.
105
+ */
106
+ function liveGrants(comments) {
107
+ const list = Array.isArray(comments) ? comments : [];
108
+ const sorted = [...list].sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));
109
+
110
+ let lastRevokeAt = null;
111
+ for (const c of sorted) {
112
+ const body = String(c.body || '').trim();
113
+ if (REVOKE_RE.test(body)) {
114
+ if (lastRevokeAt === null || c.createdAt > lastRevokeAt) lastRevokeAt = c.createdAt;
115
+ }
116
+ }
117
+
118
+ const live = [];
119
+ for (const c of sorted) {
120
+ const body = String(c.body || '').trim();
121
+ const m = body.match(GRANT_RE);
122
+ if (!m) continue;
123
+ const at = c.createdAt;
124
+ const cancelled = lastRevokeAt !== null && lastRevokeAt > at;
125
+ if (cancelled) continue;
126
+ live.push({
127
+ branch: m[1],
128
+ trunk: m[2],
129
+ redSha: m[3],
130
+ evidenceSha: m[4],
131
+ host: m[5],
132
+ at,
133
+ login: (c.author && c.author.login) || '',
134
+ authorAssociation: c.authorAssociation || '',
135
+ });
136
+ }
137
+ return live;
138
+ }
139
+
140
+ /** Association values this module treats as trustworthy enough to write a permission a scheduled
141
+ * driver will rely on — identical set and identical reasoning to migration-grant.js's. */
142
+ const { TRUSTED_ASSOCIATIONS, authorIsHuman, labelApplierIsHuman } = require('./trust-humans.js');
143
+
144
+ /**
145
+ * One issue's verdict for a branch about to ship, against the trunk sha it is CURRENTLY red at
146
+ * and the evidence run CURRENTLY measured for the branch's head.
147
+ *
148
+ * `record` is exactly what `git.ghIssueView(repo, num, ['state', 'labels', 'comments'])` returns,
149
+ * or `null` when that read FAILED — never treat `null` as "no grant" (see migration-grant.js's
150
+ * identical warning; the caller must fail closed on a failed read exactly as hard as on a
151
+ * confirmed absence).
152
+ *
153
+ * `redTrunkSha` is the trunk head sha the caller measured as CURRENTLY red — passed in, never
154
+ * re-derived here, because this module is pure. `evidence` is `{ok, sha}` — `ok` true only for a
155
+ * completed, successful run measured on `branch`'s current head; `sha` is that head's sha. Passing
156
+ * `evidence: null` means the caller's own read of the branch's run FAILED — refuses, same
157
+ * fail-closed posture as a null `record`.
158
+ *
159
+ * `labelName` is passed in rather than imported from labels.js, keeping this module free of any
160
+ * dependency beyond its own two regexes — identical reasoning to migration-grant.js.
161
+ *
162
+ * Order of checks: cheapest/most-fundamental first, each with a distinct actionable reason string.
163
+ *
164
+ * `opts` (#407) — OPTIONAL `{ trust, labelActors }`, the same contract as migration-grant.js's
165
+ * evaluateIssue: absent/undeclared trust keeps the association check byte-identical; declared, the
166
+ * grant author and the label's latest applier must both be listed in trust-humans.
167
+ */
168
+ function evaluateIssue(record, branch, trunk, redTrunkSha, evidence, issueNum, labelName, opts) {
169
+ const trust = opts && opts.trust;
170
+ const issue = issueNum;
171
+ if (!record) {
172
+ return { issue, ok: false, grant: null,
173
+ reason: `#${issue} could not be read from the tracker — a failed read is never a grant` };
174
+ }
175
+ if (record.state !== 'OPEN') {
176
+ return { issue, ok: false, grant: null,
177
+ reason: `#${issue} is ${record.state || 'not open'} — a grant expires when its issue closes` };
178
+ }
179
+ const labelNames = (record.labels || []).map((l) => (l && typeof l === 'object' ? l.name : l));
180
+ if (!labelNames.includes(labelName)) {
181
+ return { issue, ok: false, grant: null,
182
+ reason: `#${issue} does not carry the \`${labelName}\` label` };
183
+ }
184
+ const grants = liveGrants(record.comments);
185
+ if (grants.length === 0) {
186
+ return { issue, ok: false, grant: null,
187
+ reason: `#${issue} carries the label but has no live grant comment (revoked, or never posted)` };
188
+ }
189
+ const g = grants[grants.length - 1]; // most recent live grant
190
+ if (g.branch !== branch) {
191
+ return { issue, ok: false, grant: g,
192
+ reason: `#${issue}'s grant is bound to branch "${g.branch}", not "${branch}"` };
193
+ }
194
+ const who = authorIsHuman(g, trust);
195
+ if (!who.ok) {
196
+ return { issue, ok: false, grant: g,
197
+ reason: trust && trust.declared
198
+ ? `#${issue}'s grant is not a human's: ${who.reason}`
199
+ : `#${issue}'s grant was posted by ${who.reason}` };
200
+ }
201
+ if (g.trunk !== trunk || g.redSha !== redTrunkSha) {
202
+ return { issue, ok: false, grant: g,
203
+ reason: `#${issue}'s grant was reviewed against \`${g.trunk}\`@\`${g.redSha}\`, not the current \`${trunk}\`@\`${redTrunkSha}\` — trunk moved since the review, and the new head was never reviewed` };
204
+ }
205
+ if (!evidence) {
206
+ return { issue, ok: false, grant: g,
207
+ reason: `#${issue}'s grant could not be checked against the branch's current CI run — a failed evidence read is never a grant` };
208
+ }
209
+ if (!evidence.ok) {
210
+ return { issue, ok: false, grant: g,
211
+ reason: `#${issue}'s grant requires a completed, successful CI run on \`${branch}\`'s current head — none exists` };
212
+ }
213
+ if (evidence.sha !== g.evidenceSha) {
214
+ return { issue, ok: false, grant: g,
215
+ reason: `#${issue}'s grant was reviewed against evidence run \`${g.evidenceSha}\`, but \`${branch}\`'s head is now \`${evidence.sha}\` — the branch moved since the human reviewed it` };
216
+ }
217
+ if (trust && trust.declared) {
218
+ // #407 Wanted 2 — the label applier, read last: only once the grant would otherwise pass.
219
+ let actors = null;
220
+ try { actors = opts && typeof opts.labelActors === 'function' ? opts.labelActors(issue) : null; } catch (_) { actors = null; }
221
+ const lab = labelApplierIsHuman(actors, trust, labelName);
222
+ if (!lab.ok) return { issue, ok: false, grant: g, reason: `#${issue}: ${lab.reason}` };
223
+ }
224
+ return { issue, ok: true, grant: g, reason: '' };
225
+ }
226
+
227
+ /**
228
+ * The ship set's verdict — every issue the branch carries, not just the subset that would close.
229
+ * A red-trunk merge cannot be mechanically attributed to one member of a group branch, so if ANY
230
+ * claimed issue lacks a valid grant, the whole set fails — one granted issue must never smuggle an
231
+ * unreviewed red-trunk merge in for its siblings. Identical reasoning to migration-grant.js's
232
+ * evaluateShipSet, including the NON-VACUITY guard: `[].every(...)` is `true` in JavaScript, and a
233
+ * branch with ZERO claimed issues must NOT read as granted by default.
234
+ *
235
+ * `records` maps issue number → the `ghIssueView` result for that issue, or `null` on a failed
236
+ * read (the caller's job, not this function's).
237
+ */
238
+ function evaluateShipSet(issues, records, branch, trunk, redTrunkSha, evidence, labelName, opts) {
239
+ const list = Array.isArray(issues) ? issues : [];
240
+ if (list.length === 0) {
241
+ return { ok: false, granted: [],
242
+ missing: [{ issue: null, reason: 'no claimed issue on this branch could carry a grant' }] };
243
+ }
244
+ const granted = [];
245
+ const missing = [];
246
+ for (const n of list) {
247
+ const v = evaluateIssue(records ? records[n] : null, branch, trunk, redTrunkSha, evidence, n, labelName, opts);
248
+ if (v.ok) granted.push({ issue: n, branch: v.grant.branch, by: v.grant.login, at: v.grant.at, redSha: v.grant.redSha, evidenceSha: v.grant.evidenceSha });
249
+ else missing.push({ issue: n, reason: v.reason });
250
+ }
251
+ return { ok: missing.length === 0, granted, missing };
252
+ }
253
+
254
+ /**
255
+ * Whether trunk went green at some point strictly after `priorAtIso` (#229) — pure, taking `runs`
256
+ * as plain data so it is testable without git/gh. Compares INSTANTS via `Date.parse`, never raw ISO
257
+ * strings: `git log --format=%aI` reports the machine's LOCAL UTC offset (`2026-08-15T11:21:46+09:00`)
258
+ * while `gh run list --json createdAt` is always UTC (`2026-08-15T09:57:00Z`). String comparison
259
+ * diverges at the offset digits — `"...T09:57:00Z" > "...T11:21:46+09:00"` reads false even though
260
+ * the run is 7.6 hours LATER as an instant — which can rank a truly later run as "before" the prior
261
+ * grant merge, permanently wedging `stackingVerdict`'s second-grant path once it happens once (#229).
262
+ *
263
+ * `NaN` on either side (an unparseable date) counts as "cannot prove it went green" — the same
264
+ * conservative posture the caller already takes on a JSON parse failure below.
265
+ */
266
+ function wentGreenSince(runs, priorAtIso) {
267
+ const priorAt = Date.parse(priorAtIso);
268
+ if (Number.isNaN(priorAt) || !Array.isArray(runs)) return false;
269
+ return runs.some((r) => {
270
+ if (!r || r.status !== 'completed' || r.conclusion !== 'success') return false;
271
+ const at = Date.parse(r.createdAt);
272
+ return !Number.isNaN(at) && at > priorAt;
273
+ });
274
+ }
275
+
276
+ /**
277
+ * Anti-stacking verdict (#105 guard 2) — pure, used by the `colab ci-grant` CREATE path (tools/
278
+ * colab), NOT by ship's read path above (ship only ever re-checks a grant already made; whether a
279
+ * NEW one may be MADE is a separate, narrower question this function answers).
280
+ *
281
+ * `trunkIsRed` — the caller's OWN measurement of whether trunk currently has a completed,
282
+ * successful run. Refuses outright when trunk is NOT red: an exemption with nothing to exempt is a
283
+ * loaded gun sitting on an issue, never a no-op grant.
284
+ *
285
+ * `priorGrantMerge` — `null` when no `CI-Grant:`-trailer merge was found on trunk since the last
286
+ * time trunk was confirmed green (the caller's job to search, via `git log --grep`), or
287
+ * `{sha, at}` naming the most recent one. When one exists, a second grant is refused UNLESS trunk
288
+ * has gone green at some point since that merge (i.e. the red the new grant would exempt is a
289
+ * DIFFERENT, later red than the one the prior grant fixed) — the caller signals this via
290
+ * `redSince`, `null`/absent meaning "still the same continuous red".
291
+ */
292
+ function stackingVerdict({ trunkIsRed, priorGrantMerge, redContinuousSincePriorGrant }) {
293
+ if (!trunkIsRed) {
294
+ return { ok: false, reason: 'trunk is not currently red — nothing for a CI grant to exempt' };
295
+ }
296
+ if (priorGrantMerge && redContinuousSincePriorGrant) {
297
+ return { ok: false, reason: `a CI grant already merged ${priorGrantMerge.sha} against this red trunk and trunk has been red ever since — a second exemption is how a permanently broken repo ships anyway. Revert the bad merge or fix trunk by hand instead of granting again.` };
298
+ }
299
+ return { ok: true, reason: '' };
300
+ }
301
+
302
+ module.exports = {
303
+ GRANT_MARK, REVOKE_MARK, GRANT_RE, REVOKE_RE,
304
+ grantCommentBody, revokeCommentBody,
305
+ liveGrants, TRUSTED_ASSOCIATIONS,
306
+ evaluateIssue, evaluateShipSet, stackingVerdict, wentGreenSince,
307
+ };
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+ /**
3
+ * Shared "is this non-completed CI run merely slow, or structurally WEDGED?" verdict (#155).
4
+ *
5
+ * `shipCiCheck` (tools/colab) and `ci-grant`'s create path used to answer this independently and
6
+ * disagreed on the exact state that motivated this module: a queued run, created during a GitHub
7
+ * Actions incident, with ZERO jobs and no movement for ~7h. `shipCiCheck` called it SELF_CLEARING
8
+ * ("still running, retry later" — advice that can never be taken for a run that will never move) and
9
+ * therefore never consulted a grant. `ci-grant`'s inline `!(status==='completed' && conclusion===
10
+ * 'success')` called the SAME run red, happily minted a grant, and `ship` then silently ignored it —
11
+ * a grant that looks live in `--list` and is inert at the only place it is meant to be read. One
12
+ * function, called from both places, closes the gap between them BY CONSTRUCTION rather than by
13
+ * discipline.
14
+ *
15
+ * PURE BY CONSTRUCTION, same posture as ci-grant.js / migration-grant.js / shipguard.js: signals in,
16
+ * verdict out. No git, no network, no `gh`, no clock read unless `nowMs` is omitted (and even then
17
+ * only `Date.now()`, never a spawned process) — every branch is directly reachable from
18
+ * `node --test`, unlike the shell-backed functions in tools/colab this module exists to unblock.
19
+ *
20
+ * Ruling (2026-08-08, option C — both signals, reclassify to HUMAN_GATED):
21
+ * - B (primary): the run's job list is EMPTY. No runner has ever picked it up — the measured shape
22
+ * of a billing lockout or a dead runner pool, and #155's actual incident. Checkable the instant
23
+ * the run is read; no waiting required.
24
+ * - A (backstop): the run is older than WEDGE_AGE_HOURS. Generous on purpose — never mistake an
25
+ * ordinary slow CI run for a wedge — and it exists ONLY to catch the case B cannot: a runner DID
26
+ * claim the run (jobs is non-empty) and then died mid-job, so the job list is real but frozen.
27
+ *
28
+ * Either signal alone is sufficient; both point to the same reclassification (HUMAN_GATED, not red,
29
+ * not green — "a human must look", the same verdict `ci-grant`'s exemption exists to act on).
30
+ *
31
+ * Amendment (#171, 2026-08-13): signal B originally fired with no age floor at all, so a run read
32
+ * inside the window between creation and GitHub actually materializing its job list — real, and the
33
+ * realistic path into it is back-to-back ships — had `jobCount === 0` while perfectly healthy, and
34
+ * classified HUMAN_GATED. Consequence was mild (routes to the ci-grant door, never merges anything it
35
+ * shouldn't) but false. ZERO_JOBS_AGE_FLOOR_MINUTES below it, zero jobs is read as "not measured yet",
36
+ * not "wedged" — chosen at the top of the issue's proposed 60–120s range for margin, since the true
37
+ * materialization window was not re-measured empirically here. Costs nothing against the signal's
38
+ * actual target: a billing lockout or dead runner pool leaves a run at zero jobs for far longer than
39
+ * two minutes, so the floor never masks a real wedge, only the moment right after creation.
40
+ */
41
+
42
+ // Generous on purpose (see doc comment above) — an ordinary run finishes in minutes to tens of
43
+ // minutes even on a slow repo; this threshold only exists to catch a runner that claimed a job and
44
+ // then silently died, which the empty-jobs signal cannot see.
45
+ const WEDGE_AGE_HOURS = 6;
46
+
47
+ // #171: below this age, zero jobs means "GitHub hasn't materialized the job list yet", not "wedged".
48
+ // Chosen at the top of the issue's proposed 60–120s range — cheap insurance, since the floor only
49
+ // ever delays signal B by up to two minutes and never blinds it (a real wedge stays at zero jobs for
50
+ // hours, not minutes).
51
+ const ZERO_JOBS_AGE_FLOOR_MINUTES = 2;
52
+
53
+ function hoursSince(iso, nowMs) {
54
+ if (!iso) return null;
55
+ const t = Date.parse(iso);
56
+ if (Number.isNaN(t)) return null;
57
+ const now = nowMs != null ? nowMs : Date.now();
58
+ return (now - t) / 3600000;
59
+ }
60
+
61
+ /**
62
+ * `run` is the `{status, conclusion, sha, createdAt, jobCount}` shape — `createdAt`/`jobCount` may be
63
+ * null when not measured (job count is fetched lazily by the caller, only for a run already known to
64
+ * be non-completed; see tools/lib/git.js `ghRunJobCount`'s doc comment for why).
65
+ *
66
+ * Only meaningful for a run whose status is neither `'completed'` nor `'none'` — a completed run is
67
+ * never wedged by definition (it finished, however it finished), and `'none'` means no run exists at
68
+ * all, a different and already-handled case (HUMAN_GATED — "CI is not wired for this ref").
69
+ *
70
+ * Returns `{ wedged, reason }`. `reason` is null when `wedged` is false.
71
+ */
72
+ function wedgedVerdict(run, opts = {}) {
73
+ if (!run || run.status === 'completed' || run.status === 'none') return { wedged: false, reason: null };
74
+ const age = hoursSince(run.createdAt, opts.nowMs);
75
+ if (run.jobCount === 0) {
76
+ // #171: no createdAt (age unknown) never manufactures a positive here, same posture as the age
77
+ // backstop below when createdAt is missing/unparseable — a missing signal must not wedge on its own.
78
+ const floorHours = ZERO_JOBS_AGE_FLOOR_MINUTES / 60;
79
+ if (age !== null && age >= floorHours) {
80
+ return {
81
+ wedged: true,
82
+ reason: `zero jobs — no runner has ever picked it up (unmoving for ${age.toFixed(2)}h, past the ${ZERO_JOBS_AGE_FLOOR_MINUTES}m floor)`,
83
+ };
84
+ }
85
+ return { wedged: false, reason: null };
86
+ }
87
+ if (age !== null && age >= WEDGE_AGE_HOURS) {
88
+ return { wedged: true, reason: `status=${run.status} for ${age.toFixed(1)}h (>= ${WEDGE_AGE_HOURS}h backstop)` };
89
+ }
90
+ return { wedged: false, reason: null };
91
+ }
92
+
93
+ // #413: how long after a trunk commit "no run at this sha" is still the ordinary state. GitHub
94
+ // creates a push run seconds after the push, but a ship reading trunk right after another ship
95
+ // landed it can get there first. Ten minutes covers queueing on a busy account; past it, an empty
96
+ // read goes back to meaning what it always meant — CI is not wired, or never started.
97
+ const EMPTY_READ_GRACE_MINUTES = 10;
98
+
99
+ /**
100
+ * Is an empty CI read of a sha still inside the window where a run may simply not exist YET (#413)?
101
+ * `committedAtMs` is the sha's committer time (null when unknown). Unknown age never manufactures a
102
+ * grace — same posture as wedgedVerdict's missing createdAt: a missing signal must not flip a class.
103
+ *
104
+ * Returns `{ fresh, minutes }` — `minutes` is the measured age, or null when unknown.
105
+ */
106
+ function emptyReadVerdict(committedAtMs, opts = {}) {
107
+ if (committedAtMs == null || !Number.isFinite(committedAtMs)) return { fresh: false, minutes: null };
108
+ const now = opts.nowMs != null ? opts.nowMs : Date.now();
109
+ const minutes = (now - committedAtMs) / 60000;
110
+ return { fresh: minutes >= 0 && minutes < EMPTY_READ_GRACE_MINUTES, minutes };
111
+ }
112
+
113
+ module.exports = { WEDGE_AGE_HOURS, ZERO_JOBS_AGE_FLOOR_MINUTES, EMPTY_READ_GRACE_MINUTES, wedgedVerdict, emptyReadVerdict };
@@ -0,0 +1,212 @@
1
+ 'use strict';
2
+ /**
3
+ * The claim-comment WIRE FORMAT and the two readers built on it: `liveClaimComments` (which
4
+ * `🔒 Claimed` comments still stand) and `tieBreakVerdict` (who wins a simultaneous claim race).
5
+ * Moved out of tools/colab by #369/#375 so both rules are unit-testable as pure functions — the
6
+ * same split every other tools/lib module keeps from its caller. tools/colab keeps the writers
7
+ * (`claimCommentBody`, `postClaimComment`, `postReleaseComment`, `yieldIssue`) because they need
8
+ * the clock, the machine id and the tracker.
9
+ *
10
+ * These strings are a STABLE WIRE FORMAT: the refusal path, the tie-break, and dashboards grep
11
+ * them. Do not reword casually — an older colab on another machine parses what this one writes.
12
+ */
13
+
14
+ const claimIdentity = require('./claim-identity');
15
+ const machine = require('./machine');
16
+
17
+ const CLAIM_MARK = '🔒 Claimed';
18
+ const RELEASE_MARK = '✅ Released';
19
+ // #378: how far BEFORE our own claim a rival's live claim can be and still count as "simultaneous".
20
+ // Racers post within seconds of each other; 10 minutes is deliberately generous so a slow `gh` never
21
+ // splits a real race, while a claim weeks old — abandoned, or released only in prose — is not a race.
22
+ const RACE_WINDOW_MS = 10 * 60 * 1000;
23
+ // Parses a claim comment body back into {worktree, branch, host, date}. The `· <host>` field is
24
+ // what lets the tie-break tell two machines of the SAME GitHub user apart. On a public destination
25
+ // it carries an opaque `h:` token instead of the raw name (#369, machine.js `hostToken`) — same
26
+ // field, same position, so this regex and every older parser read both shapes. The optional
27
+ // trailing `· session <value>` (added 2026-07) is captured separately by SESSION_RE so this regex
28
+ // stays byte-stable for session-less comments.
29
+ const CLAIM_RE = /🔒 Claimed — worktree `([^`]*)` · branch `([^`]*)` · host `([^`]*)` · (\S+)/;
30
+ // The `· session <field>` tail, captured as the rest of the line. parseSessionField() then decodes
31
+ // the THREE shapes it can take — `[name](url)`, a bare URL, or a bare name — plus the legacy
32
+ // plain-URL form written before sessionName existed.
33
+ const SESSION_RE = /· session (.+)$/;
34
+ // #327: the claimant's machine, as the public `m:` digest (tools/lib/machine.js `machineToken`),
35
+ // written AFTER the timestamp and BEFORE the session suffix — so CLAIM_RE's four groups and
36
+ // SESSION_RE's end anchor both parse a new comment exactly as they parse a legacy one, and a legacy
37
+ // comment (no such field) simply has no machine and is compared by host.
38
+ const MACHINE_RE = /· machine `(m:[0-9a-f]{12})`/;
39
+ // A yield: the loser of a race releases, naming the winner by its identity string
40
+ // (`claimIdentity.identityString` — `login@host`, or `login@host#session` under the fine setting).
41
+ const YIELD_RE = /^✅ Released \(yielded — earlier claim by (.+?) wins\)/;
42
+
43
+ /**
44
+ * Decode the `· session <field>` tail of a claim comment into { sessionName, session }. Accepts:
45
+ * `[name](url)` → both; bare `https://…`/`session_…` → url only; any other bare token → name.
46
+ * The bare-URL branch is exactly the LEGACY format written before sessionName existed, so old
47
+ * comments keep parsing. Returns empty strings when there is no session tail.
48
+ */
49
+ function parseSessionField(body) {
50
+ const m = String(body).match(SESSION_RE);
51
+ if (!m) return { sessionName: '', session: '' };
52
+ const v = m[1].trim();
53
+ const link = v.match(/^\[([^\]]*)\]\((.*)\)$/);
54
+ if (link) return { sessionName: link[1], session: link[2] };
55
+ // #306: the shape test lives in claimIdentity.looksLikeSessionId — one copy of the rule.
56
+ if (claimIdentity.looksLikeSessionId(v)) return { sessionName: '', session: v };
57
+ return { sessionName: v, session: '' };
58
+ }
59
+
60
+ /** `login@host[#session]` → its parts. Logins cannot contain `@`, hosts cannot contain `#`. */
61
+ function parseIdentity(s) {
62
+ const str = String(s || '').trim();
63
+ const at = str.indexOf('@');
64
+ if (at <= 0) return null;
65
+ const rest = str.slice(at + 1);
66
+ const hash = rest.indexOf('#');
67
+ return {
68
+ login: str.slice(0, at),
69
+ host: hash === -1 ? rest : rest.slice(0, hash),
70
+ session: hash === -1 ? '' : rest.slice(hash + 1),
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Is claim `c` the one a yield NAMED as its winner? Login exact, host by `sameHostName` (so a
76
+ * yield naming the `h:` token matches a claim that carried the raw name, and the reverse), session
77
+ * only when both sides carry one — the named identity was built under the yielder's granularity,
78
+ * which need not be the reader's.
79
+ */
80
+ function isNamedWinner(c, named) {
81
+ if (!named || c.login !== named.login) return false;
82
+ if (!machine.sameHostName(c.host, named.host)) return false;
83
+ if (named.session && c.session && named.session !== c.session) return false;
84
+ return true;
85
+ }
86
+
87
+ /**
88
+ * Every `✅ Released` on the issue, classified. `yield` carries the named winner; `release` is a
89
+ * plain release (`colab release`, `worktree rm`, a hand-typed one).
90
+ */
91
+ function releaseComments(sorted) {
92
+ const out = [];
93
+ for (const c of sorted) {
94
+ const body = String(c.body || '').trim();
95
+ if (!body.startsWith(RELEASE_MARK)) continue;
96
+ const login = (c.author && c.author.login) || '';
97
+ const y = body.match(YIELD_RE);
98
+ if (y) out.push({ kind: 'yield', login, at: c.createdAt, winner: parseIdentity(y[1]) });
99
+ else out.push({ kind: 'release', login, at: c.createdAt });
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /**
105
+ * Live claim comments on an issue. Returns [{login, host, machine, session, sessionName, at,
106
+ * identity}], `at` = the comment's real GitHub createdAt (authoritative, sub-second). `identity`
107
+ * is built from `comps` (claim-identity.js `components()`, #267); the raw fields are returned too
108
+ * for callers that need `sameClaimant`'s degrade-on-missing comparison.
109
+ *
110
+ * A claim is CANCELLED by a later release, under two rules (#375):
111
+ *
112
+ * 1. A PLAIN `✅ Released` cancels every claim posted before it, WHOEVER posted either. A plain
113
+ * release is `colab release` / `worktree rm` / a human's own, and since #363 colab's release
114
+ * removes `in-progress` and unassigns whichever account applied it — the claim is over at the
115
+ * label layer no matter whose it was, so the comment layer must agree. Keying this on the
116
+ * release's AUTHOR (the pre-#375 rule) left a claim released under a second account live in
117
+ * the comments forever; 24 days later it "won" a race against a fresh claim on free work.
118
+ * The cost the issue named — a stray release cancelling a genuinely live claim — is the cost
119
+ * the label layer already pays for that same release, not a new one.
120
+ * 2. A YIELD (`✅ Released (yielded — earlier claim by <id> wins)`) cancels only its own AUTHOR's
121
+ * earlier claims, and never the claim it named as the winner. A yield is one racer standing
122
+ * down; it is not a release of the issue. Under the author-keyed rule a same-account yield
123
+ * (machine Y yielding to machine X of one login) also cancelled X's WINNING claim, so the
124
+ * layer that the cross-machine refusal (#325) reads went blank the moment X won.
125
+ *
126
+ * Pure function of the comment list: every reader of the same comments computes the same live
127
+ * set, which is what `tieBreakVerdict`'s convergence rests on. Alternatives weighed:
128
+ * docs/adr/375-release-cancels-any-earlier-claim.md.
129
+ */
130
+ function liveClaimComments(comments, comps) {
131
+ comps = comps || claimIdentity.DEFAULT_COMPONENTS;
132
+ const sorted = [...(comments || [])].sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));
133
+ const releases = releaseComments(sorted);
134
+ const live = [];
135
+ for (const c of sorted) {
136
+ const body = String(c.body || '').trim();
137
+ const m = body.match(CLAIM_RE);
138
+ if (!m) continue;
139
+ const login = (c.author && c.author.login) || '';
140
+ const host = m[3];
141
+ const { session, sessionName } = parseSessionField(body); // handles [name](url) / url / name / legacy
142
+ const mm = body.match(MACHINE_RE); // #327 — absent on a legacy comment: compared by host
143
+ const machineTok = mm ? mm[1] : '';
144
+ const at = c.createdAt;
145
+ const entry = { login, host, machine: machineTok, session, sessionName, at };
146
+ const cancelled = releases.some((r) => r.at > at && (r.kind === 'release'
147
+ || (r.login === login && !isNamedWinner(entry, r.winner))));
148
+ if (!cancelled) live.push({ ...entry, identity: claimIdentity.identityString({ login, host, session }, comps) });
149
+ }
150
+ return live;
151
+ }
152
+
153
+ /**
154
+ * Deterministic verdict on the simultaneous-claim race. Given the issue's comments and our own
155
+ * identity (`myLogin`/`myHost`/`mySession`/`myMachine`): if a live claim that is NOT us under
156
+ * `comps` (`sameClaimant`, #267) is EARLIER than our own earliest live claim, by no more than
157
+ * `RACE_WINDOW_MS` → we lost (returns the winner). Exact-timestamp ties break on identity string
158
+ * (lexicographically smaller identity wins), so both racers, reading the same comments, reach the
159
+ * same verdict independently.
160
+ *
161
+ * The window (#378): a live claim posted more than `RACE_WINDOW_MS` before ours is not a rival in a
162
+ * race — it is a claim nobody released with a marker (abandoned, or released in prose only), and
163
+ * without the bound it won every later tie-break on the issue, forever. A claim that is really still
164
+ * held never reaches this function: the refusal gate (`in-progress` + assignee, and #325's
165
+ * other-machine check) refuses it first. Comment timestamps only — still a pure function of the
166
+ * comment list, so convergence holds. docs/adr/378-tie-break-race-window.md.
167
+ *
168
+ * `myHost` is the RAW hostname; our own comment may carry its `h:` token (#369, public
169
+ * destination) — `sameClaimant` → `sameHost` → `sameHostName` matches the two.
170
+ *
171
+ * Anchors on our EARLIEST live claim, not the latest (#264/#267 together): a re-claim that corrects
172
+ * a record posts a SECOND comment from us, and anchoring on the latest of those would let that
173
+ * correction restart our own priority — costing us a race we had already won.
174
+ */
175
+ function tieBreakVerdict(comments, myLogin, myHost, mySession, comps, myMachine = null) {
176
+ comps = comps || claimIdentity.DEFAULT_COMPONENTS;
177
+ const live = liveClaimComments(comments, comps);
178
+ const me = { login: myLogin, host: myHost, session: mySession || '', machine: myMachine || '' };
179
+ const mine = live
180
+ .filter((c) => claimIdentity.sameClaimant(c, me, comps))
181
+ .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))[0]; // our EARLIEST live claim
182
+ if (!mine) return { lost: false }; // our own comment not visible yet → don't yield to a phantom
183
+ let winner = null;
184
+ for (const c of live) {
185
+ if (claimIdentity.sameClaimant(c, me, comps)) continue; // never yield to ourselves
186
+ const earlier = c.at < mine.at || (c.at === mine.at && c.identity < mine.identity);
187
+ if (!earlier) continue;
188
+ if (Date.parse(mine.at) - Date.parse(c.at) > RACE_WINDOW_MS) continue; // #378: not a race
189
+ if (!winner || c.at < winner.at || (c.at === winner.at && c.identity < winner.identity)) winner = c;
190
+ }
191
+ return winner ? { lost: true, winner } : { lost: false };
192
+ }
193
+
194
+ /**
195
+ * The yield comment body. `redact` (#369: the destination may not name a host) swaps the winner's
196
+ * host for its `h:` token — the winner's own comment may predate redaction and carry the raw name,
197
+ * and a yield must not republish it. `isNamedWinner` matches either spelling back.
198
+ */
199
+ function yieldReleaseBody(winner, { redact = false } = {}) {
200
+ let id = winner.identity;
201
+ if (redact) {
202
+ const head = `${winner.login}@${winner.host}`;
203
+ const tail = id.startsWith(head) ? id.slice(head.length) : '';
204
+ id = `${winner.login}@${machine.hostToken(winner.host)}${tail}`;
205
+ }
206
+ return `${RELEASE_MARK} (yielded — earlier claim by ${id} wins)`;
207
+ }
208
+
209
+ module.exports = {
210
+ CLAIM_MARK, RELEASE_MARK, RACE_WINDOW_MS, CLAIM_RE, SESSION_RE, MACHINE_RE, YIELD_RE,
211
+ parseSessionField, parseIdentity, isNamedWinner, liveClaimComments, tieBreakVerdict, yieldReleaseBody,
212
+ };