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

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +312 -3
  3. package/README.vi.md +281 -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 +13806 -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 +278 -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-endpoint.js +170 -0
  63. package/tools/lib/notify.js +188 -0
  64. package/tools/lib/npm-publish-guard.js +242 -0
  65. package/tools/lib/orphan-worktree.js +127 -0
  66. package/tools/lib/owner-branch.js +182 -0
  67. package/tools/lib/place.js +782 -0
  68. package/tools/lib/ports.js +167 -0
  69. package/tools/lib/procs.js +185 -0
  70. package/tools/lib/readiness.js +240 -0
  71. package/tools/lib/records.js +185 -0
  72. package/tools/lib/refs-brake.js +95 -0
  73. package/tools/lib/release-channel.js +99 -0
  74. package/tools/lib/release-cut.js +822 -0
  75. package/tools/lib/release-finalize.js +521 -0
  76. package/tools/lib/release-policy.js +358 -0
  77. package/tools/lib/release-tag.js +225 -0
  78. package/tools/lib/ship-batch.js +277 -0
  79. package/tools/lib/ship-roles.js +71 -0
  80. package/tools/lib/ship-target-sync.js +181 -0
  81. package/tools/lib/shipguard.js +317 -0
  82. package/tools/lib/shipped-branch.js +56 -0
  83. package/tools/lib/solo.js +213 -0
  84. package/tools/lib/squash.js +515 -0
  85. package/tools/lib/stale-base.js +70 -0
  86. package/tools/lib/stamp.js +740 -0
  87. package/tools/lib/state.js +262 -0
  88. package/tools/lib/teardown.js +83 -0
  89. package/tools/lib/trust-humans.js +104 -0
  90. package/tools/lib/util.js +98 -0
  91. package/tools/lib/wake.js +188 -0
  92. package/tools/lib/workflow-triggers.js +273 -0
  93. package/tools/lib/writes-authority.js +237 -0
  94. package/tools/lib/yaml.js +101 -0
  95. package/bin/cli.js +0 -3
@@ -0,0 +1,515 @@
1
+ 'use strict';
2
+ /**
3
+ * Composing the squash-commit message for `colab ship` (Phase B1).
4
+ *
5
+ * This module is PURE — it takes an array of already-read commits and returns a string. All git
6
+ * I/O stays in the CLI. That split exists so this logic can be unit-tested: `tools/colab` has no
7
+ * test harness, `tools/lib/*.test.js` is wired into CI, and the bug this module was extracted to
8
+ * fix was invisible precisely because nothing tested it.
9
+ *
10
+ * THE BUG IT FIXES. The subject used to be the branch's NEWEST commit, verbatim. On a well-run
11
+ * branch the newest commit is the SMALLEST — the docs pass you do last — so `feat` work shipped
12
+ * under a `docs:` subject. Release notes group on that prefix (CONVENTIONS §4), so the feature was
13
+ * invisible in the changelog: nothing failed, CI stayed green, the issues closed. Two such subjects
14
+ * are baked into a published tag and cannot be corrected.
15
+ *
16
+ * WHAT REPLACES IT. The subject comes from the HIGHEST-WEIGHT commit on the branch (breaking >
17
+ * feat > fix > perf > refactor > docs > test > chore), ties going to the OLDEST — the commit that
18
+ * established what the branch is for; later commits of the same type are follow-ups. A branch with
19
+ * one commit therefore behaves exactly as before. A branch where nothing carries a Conventional
20
+ * Commit prefix also falls back to the old behaviour (newest), because there is nothing to weigh.
21
+ *
22
+ * WHAT IS DELIBERATELY UNCHANGED. The body design was never at fault: `Closes #N` for every claimed
23
+ * issue, the other subjects as bullets, `chore(sync)` merge-noise filtered, footers preserved. The
24
+ * one body change is a consequence of the subject change — since the chosen commit may no longer be
25
+ * the newest, trailers are harvested from EVERY commit on the branch rather than only the newest,
26
+ * or a `Co-Authored-By:` on the last commit would now be silently dropped.
27
+ */
28
+
29
+ /**
30
+ * Conventional Commit type → weight. Ordering follows the semantic-release convention that decides
31
+ * what a change means to a consumer: feat is a minor bump, fix a patch, the rest cosmetic. The
32
+ * numbers are spaced so a type can be inserted without renumbering; only the ORDER is meaningful.
33
+ * This is the RECOGNISED set — the one place it lives (#261) — documented for adopters in
34
+ * CONVENTIONS.md §4 alongside the branch-name regex; keep the two in sync by hand when either moves.
35
+ *
36
+ * `design` (#261): a deliberate spec/mockup/visual-decision commit, not a behaviour change — ranked
37
+ * above `docs` because it is typically the branch's own deliverable rather than paperwork about one,
38
+ * and below `refactor`/`revert` because, like `docs`, it changes nothing a consumer runs.
39
+ */
40
+ const TYPE_WEIGHT = {
41
+ feat: 70,
42
+ fix: 60,
43
+ perf: 50,
44
+ refactor: 40,
45
+ revert: 40,
46
+ design: 35,
47
+ docs: 30,
48
+ test: 20,
49
+ build: 15,
50
+ ci: 15,
51
+ style: 12,
52
+ chore: 10,
53
+ };
54
+
55
+ /**
56
+ * Weight given to a commit whose subject IS Conventional-Commit-shaped (`type(scope): text`) but
57
+ * whose `type` is not a key of `TYPE_WEIGHT` — `wip:`, `spike:`, a future adopter-invented type this
58
+ * table has not caught up with yet (#261). Deliberately below every named type (lower than `chore`,
59
+ * the lowest), so a real headline still cannot be outranked by an unrecognised one on merit — but
60
+ * ABOVE 0 (a commit with no Conventional Commit shape at all), so an unrecognised-but-intentional
61
+ * type is no longer bucketed identically with "no signal whatsoever": on a branch where nothing else
62
+ * carries a named type, it now wins the subject over a shapeless commit instead of losing to whichever
63
+ * of the two happens to be newest (`pickSubjectIndex` rule 4). It still LOSES to any named type on a
64
+ * mixed branch — the class shrinks from "invisible" to "ranks last, and only a human's `--message`
65
+ * fixes it", per the issue's own suggested design; `unweightedCommits` below still flags it either way.
66
+ */
67
+ const UNRECOGNISED_WEIGHT = 5;
68
+
69
+ /** A breaking change outranks every non-breaking one, whatever its type. */
70
+ const BREAKING_BONUS = 1000;
71
+
72
+ const SUBJECT_RE = /^([a-z]+)(?:\(([^)]*)\))?(!)?:\s*(.+)$/;
73
+
74
+ /** Trailer keys worth carrying across a squash. An allowlist, not a general trailer parser: a
75
+ * loose `^\w+:` rule swallows ordinary prose lines ("Note: ...") and `Closes #N`, which is
76
+ * composed separately and must not be duplicated.
77
+ * `Rule-Neutral` (#272) has to survive here or the whole mechanism is dead on arrival on this
78
+ * very repo: a template edit lands on trunk as ONE squashed commit, and `templateChangedSince`
79
+ * (tools/lib/stamp.js) reads that trunk commit's trailers, never the pre-squash branch history a
80
+ * contributor actually wrote the declaration on. */
81
+ const TRAILER_RE = /^(?:Co-authored-by|Signed-off-by|Claude-Session|Reviewed-by|Rule-Neutral):\s*\S/i;
82
+
83
+ /** Sync-merge noise: a commit produced by B0 pulling trunk into the branch, not by the author. */
84
+ function isSyncNoise(subject) {
85
+ return /^chore\(sync\)/.test(String(subject || ''));
86
+ }
87
+
88
+ /** Parse a Conventional Commit subject → {type, scope, breaking, description} or null. */
89
+ function parseSubject(subject) {
90
+ const m = SUBJECT_RE.exec(String(subject || '').trim());
91
+ if (!m) return null;
92
+ return { type: m[1], scope: m[2] || null, breaking: !!m[3], description: m[4] };
93
+ }
94
+
95
+ /**
96
+ * Weight of one commit. 0 means "carries no Conventional Commit shape at all" — the true no-signal
97
+ * case, still resolved by `pickSubjectIndex`'s newest-wins fallback. A shape that IS Conventional-
98
+ * Commit-like but names a type outside `TYPE_WEIGHT` scores `UNRECOGNISED_WEIGHT` instead (#261) —
99
+ * low enough to never beat a named type, high enough to beat a truly shapeless commit. Either way
100
+ * the commit cannot claim the subject on MERIT against a named type; see `unweightedCommits` for the
101
+ * caller-facing warning, which still flags both shapes as one finding.
102
+ */
103
+ function commitWeight(commit) {
104
+ const parsed = parseSubject(commit && commit.subject);
105
+ if (!parsed) return 0;
106
+ const base = TYPE_WEIGHT[parsed.type];
107
+ const breaking = parsed.breaking || /^BREAKING[ -]CHANGE:/m.test(String((commit && commit.body) || ''));
108
+ if (base === undefined) return UNRECOGNISED_WEIGHT + (breaking ? BREAKING_BONUS : 0); // shaped, unnamed type (#261)
109
+ return base + (breaking ? BREAKING_BONUS : 0);
110
+ }
111
+
112
+ /** True when `commit`'s subject names a Conventional Commit type this repo actually weighs — the
113
+ * narrower of the two things `commitWeight` folds into one number. Exists so `unweightedCommits`
114
+ * keeps flagging an unrecognised-but-shaped commit (`wip:`, `spike:`) even though #261 gave it a
115
+ * nonzero weight: that weight only protects it from a truly shapeless commit, never from a NAMED
116
+ * type, so it still deserves the same warning as before. */
117
+ function hasRecognisedType(commit) {
118
+ const parsed = parseSubject(commit && commit.subject);
119
+ return !!parsed && TYPE_WEIGHT[parsed.type] !== undefined;
120
+ }
121
+
122
+ /**
123
+ * Commits carrying no NAMED Conventional Commit type, excluding sync-merge noise (#88). Two shapes
124
+ * land here, and both are the same finding: the type will never outrank a named one for the subject
125
+ * and will never head a changelog entry titled by it.
126
+ *
127
+ * - no Conventional Commit shape at all ("fixed the thing") — weight 0
128
+ * - a shape that isn't a recognised type — `wip:`, `spike:` — which is the more dangerous of the
129
+ * two, because it LOOKS finished. #88 Case 1 is exactly this: a branch shipping a convention
130
+ * plus +104 lines of CONVENTIONS.md landed titled `fix(labels): correct mechanical-readiness
131
+ * tests…`, because its only commit describing the deliverable was typed `wip:`. The incidental
132
+ * `fix` (weight 60) won over nothing rather than over the headline — the `wip` commit was never
133
+ * in the race. #261 gave this shape `UNRECOGNISED_WEIGHT` (5) instead of 0, so it now beats a
134
+ * truly shapeless commit for the subject — but it still loses to any NAMED type exactly as
135
+ * before, so it still belongs on this warning list. Test with `hasRecognisedType`, not a weight
136
+ * comparison — `commitWeight`'s scale conflates "unrecognised" and "shapeless" on purpose, this
137
+ * function must not.
138
+ *
139
+ * Named for a caller to WARN with, not to decide with — `pickSubjectIndex` already resolves ties
140
+ * and fallbacks correctly on its own terms; this only surfaces the blind spot at ship time instead
141
+ * of only at changelog-reading time, which is CONVENTIONS.md §4.
142
+ */
143
+ function unweightedCommits(commits) {
144
+ return (Array.isArray(commits) ? commits : [])
145
+ .filter((c) => c && !isSyncNoise(c.subject))
146
+ .filter((c) => !hasRecognisedType(c));
147
+ }
148
+
149
+ /**
150
+ * Index of the commit whose subject should title the squash. `commits` is NEWEST-FIRST (git log
151
+ * order).
152
+ *
153
+ * Rules, in order:
154
+ * 1. sync-merge noise never titles a squash (unless it is all there is);
155
+ * 2. highest weight wins — an unrecognised-but-shaped type (#261, weight `UNRECOGNISED_WEIGHT`)
156
+ * beats a truly shapeless commit here, so it is no longer a coin-flip against rule 4;
157
+ * 3. ties go to the OLDEST of the tied commits — on a branch of three `feat`s, the first one
158
+ * names the branch's purpose and the rest extend it;
159
+ * 4. if NOTHING on the branch carries any Conventional Commit shape at all (weight 0, the one
160
+ * case #261 left alone), fall back to the newest commit. There is no signal to weigh, and the
161
+ * previous behaviour is at least predictable.
162
+ */
163
+ function pickSubjectIndex(commits) {
164
+ if (!Array.isArray(commits) || commits.length === 0) return -1;
165
+ const candidates = commits.map((c, i) => ({ i, w: commitWeight(c), noise: isSyncNoise(c && c.subject) }))
166
+ .filter((c) => !c.noise);
167
+ const pool = candidates.length ? candidates : commits.map((c, i) => ({ i, w: commitWeight(c) }));
168
+ const best = Math.max(...pool.map((c) => c.w));
169
+ if (best === 0) return pool[0].i; // no Conventional Commit shape anywhere → newest, as before
170
+ // pool is newest-first, so the LAST entry at the best weight is the oldest of the tied commits.
171
+ const tied = pool.filter((c) => c.w === best);
172
+ return tied[tied.length - 1].i;
173
+ }
174
+
175
+ /** Trailer lines from every commit, newest-first, de-duplicated case-insensitively. */
176
+ function harvestTrailers(commits) {
177
+ const seen = new Set();
178
+ const out = [];
179
+ for (const c of commits || []) {
180
+ for (const line of String((c && c.body) || '').split('\n')) {
181
+ const t = line.trim();
182
+ if (!TRAILER_RE.test(t)) continue;
183
+ const key = t.toLowerCase();
184
+ if (seen.has(key)) continue;
185
+ seen.add(key);
186
+ out.push(t);
187
+ }
188
+ }
189
+ return out;
190
+ }
191
+
192
+ /**
193
+ * Full-line reference clauses ship itself composes ("Closes #17", "Refs #48", or several of either
194
+ * joined by ", "). Only a line matching this shape end-to-end is ever touched by
195
+ * `reconcileClosesRefsConflict` below — arbitrary prose that merely mentions an issue number (a
196
+ * sentence, not a trailer) is left alone, because rewriting inside a sentence is not a safe
197
+ * mechanical operation. The keyword casing mirrors the rest of this file: `[Cc]loses`, `[Rr]efs` —
198
+ * not a general case-insensitive match, and not the full GitHub closing-keyword vocabulary.
199
+ */
200
+ const REF_LINE_RE = /^(?:(?:[Cc]loses|[Rr]efs) #\d+)(?:,\s*(?:[Cc]loses|[Rr]efs) #\d+)*$/;
201
+ const REF_CLAUSE_RE = /([Cc]loses|[Rr]efs) #(\d+)/g;
202
+
203
+ /**
204
+ * Drop an inherited `Refs #N` clause for any N ship is about to CLOSE (#58).
205
+ *
206
+ * The scenario: a session writes `Refs #53` into its own commit body while the issue is still open
207
+ * (an honest trailer at the time). By the time `ship` runs, #53 is one of the issues this branch
208
+ * CLOSES — but the pure layer only ever APPENDED a missing reference; it never looked at what the
209
+ * carried text already said. The result was two contradictory, immutable trailers on one commit:
210
+ * `Closes #53` (composed) and `Refs #53` (inherited), both true-looking, one of them stale.
211
+ *
212
+ * Only a self-contained reference LINE is touched (see `REF_LINE_RE`) — this is exactly the shape
213
+ * both ship's own composed line and the live #58 report take (a commit body ending in a bare
214
+ * `Refs #53`). A clause naming an issue NOT in `closeNums` survives untouched, including a `Refs #N`
215
+ * for a number that is genuinely only in `refs` — that is not a conflict, just a duplicate the
216
+ * caller's "already present" check already declines to repeat.
217
+ *
218
+ * Deliberately NOT symmetric: an inherited `Closes #N` for a number ship intends to `Refs` (a
219
+ * tracking issue, #48) is left alone HERE — this function only ever DROPS/REWRITES a self-contained
220
+ * `Refs`/`Closes` line, and rewriting a human-authored `Closes #N` into something else would produce
221
+ * a squash message that reads correct while GitHub still closes the memory issue on merge, because
222
+ * GitHub reads the carried text regardless of what this pure layer emits.
223
+ *
224
+ * That gap is real, but as of #149 it is closed a different way — not by rewriting here, but by
225
+ * `inheritedClosingKeywordConflicts` below, which SCANS (never edits) the fully composed message for
226
+ * any GitHub closing keyword against a `--refs` number, in prose or in a self-contained line alike,
227
+ * and lets the caller (`colab ship`) REFUSE before the push. Refusing is safe to be symmetric about
228
+ * in a way rewriting never was: the operator still authors the final text, ship just declines to
229
+ * commit one that contradicts its own `--refs` intent. See that function's doc comment for the rest.
230
+ *
231
+ * @param {string} message
232
+ * @param {string[]} closeNums normalised (no leading `#`) issue numbers ship will CLOSE
233
+ * @param {Array} [conflicts] when given, one `{num, from, to}` is pushed per clause dropped —
234
+ * the caller's hook for warning a human that a hand-written trailer
235
+ * was overruled
236
+ * @returns {string}
237
+ */
238
+ function reconcileClosesRefsConflict(message, closeNums, conflicts) {
239
+ if (!closeNums || !closeNums.length) return message;
240
+ const closeSet = new Set(closeNums);
241
+ let changed = false;
242
+ const lines = String(message).split('\n').map((line) => {
243
+ const trimmed = line.trim();
244
+ if (!trimmed || !REF_LINE_RE.test(trimmed)) return line;
245
+ const kept = [];
246
+ let m;
247
+ REF_CLAUSE_RE.lastIndex = 0;
248
+ while ((m = REF_CLAUSE_RE.exec(trimmed))) {
249
+ const isRefs = /^[Rr]efs$/.test(m[1]);
250
+ const num = m[2];
251
+ if (isRefs && closeSet.has(num)) {
252
+ changed = true;
253
+ if (conflicts) conflicts.push({ num, from: 'Refs', to: 'Closes' });
254
+ continue; // drop this clause — ship's own Closes #N replaces it
255
+ }
256
+ kept.push(`${isRefs ? 'Refs' : 'Closes'} #${num}`);
257
+ }
258
+ return kept.length ? kept.join(', ') : null; // null marks the whole line for removal
259
+ });
260
+ if (!changed) return message;
261
+ return lines.filter((l) => l !== null).join('\n')
262
+ // a fully-dropped line can leave a dangling blank run — mid-message (two adjacent blank
263
+ // separators) or trailing (the dropped line was last). Collapse both; never touches content.
264
+ .replace(/\n{3,}/g, '\n\n')
265
+ .replace(/\n+$/, '');
266
+ }
267
+
268
+ /**
269
+ * Compose the full squash message.
270
+ *
271
+ * @param {Array<{subject:string, body?:string}>} commits NEWEST-FIRST, merge commits already excluded
272
+ * @param {Array<number|string>} closes claimed issue numbers to CLOSE (`Closes #N`)
273
+ * @param {Array<number|string>} refs claimed issue numbers to REFERENCE but keep
274
+ * open (`Refs #N`) — long-lived memory/tracking
275
+ * issues the branch touched but did not complete
276
+ * @param {Array} [conflicts] when given, collects `{num, from, to}` for
277
+ * every inherited trailer `spliceCloses`
278
+ * overruled — see `reconcileClosesRefsConflict`
279
+ * @param {string[]} [extraTrailerLines] COMPOSED trailer lines this call itself
280
+ * wants appended (e.g. #105's `CI-Grant:`) —
281
+ * NOT inherited from a commit body, so they
282
+ * bypass harvestTrailers entirely and are
283
+ * glued on with the identical "onto an
284
+ * existing trailer block, never mid-value"
285
+ * rule. Never widens TRAILER_KEYS/
286
+ * harvestTrailers — that allowlist is for
287
+ * trailers INHERITED from carried commits,
288
+ * a different concern from one this call
289
+ * composes itself.
290
+ * @returns {string} the commit message
291
+ *
292
+ * Layout — subject, then body blocks in this order:
293
+ * Closes #N, Refs #M one paragraph: Closes for completed issues, Refs for tracking ones,
294
+ * each skipped if the assembled text already references it that way
295
+ * - other subjects every commit except the chosen one, newest-first, sync-noise dropped
296
+ * <chosen commit's body> verbatim
297
+ * <harvested trailers> only those not already present above
298
+ * <extraTrailerLines> only those not already present above, appended last
299
+ */
300
+ function composeSquashMessage(commits, closes = [], refs = [], conflicts, extraTrailerLines = []) {
301
+ const list = Array.isArray(commits) ? commits.filter(Boolean) : [];
302
+ if (list.length === 0) return '';
303
+
304
+ const pick = pickSubjectIndex(list);
305
+ const chosen = list[pick];
306
+ const subject = String(chosen.subject || '').replace(/\s+$/, '');
307
+ const chosenBody = String(chosen.body || '').replace(/^\n+/, '').replace(/\s+$/, '');
308
+
309
+ const bullets = list
310
+ .filter((_, i) => i !== pick)
311
+ .map((c) => String(c.subject || '').trim())
312
+ .filter((s) => s && !isSyncNoise(s))
313
+ .map((s) => `- ${s}`);
314
+
315
+ // Assemble everything EXCEPT Closes first: the "already referenced?" test must run against what
316
+ // will actually ship. Testing the input instead (as the original did) can drop a `Closes #N` that
317
+ // lived in a commit body the squash does not carry — the issue then never auto-closes.
318
+ const tail = [];
319
+ if (bullets.length) tail.push(bullets.join('\n'));
320
+ if (chosenBody) tail.push(chosenBody);
321
+ let assembled = [subject, ...tail].join('\n\n');
322
+
323
+ // Case-insensitive, exactly as harvestTrailers de-duplicates: git tooling is inconsistent about
324
+ // `Co-authored-by` vs `Co-Authored-By`, and an exact-match test appends a second copy of a trailer
325
+ // the body already carries.
326
+ const present = new Set(assembled.split('\n').map((l) => l.trim().toLowerCase()));
327
+ const inheritedTrailers = harvestTrailers(list).filter((t) => !present.has(t.toLowerCase()));
328
+ if (inheritedTrailers.length) {
329
+ // Glue trailers onto an existing trailer block; otherwise start a new paragraph, so git still
330
+ // reads the last paragraph as trailers.
331
+ const lastLine = assembled.split('\n').pop().trim();
332
+ assembled += (TRAILER_RE.test(lastLine) ? '\n' : '\n\n') + inheritedTrailers.join('\n');
333
+ }
334
+
335
+ // #105: trailers THIS CALL composes itself (never inherited from a carried commit) — same
336
+ // glue-onto-a-trailer-block-never-mid-value rule, applied after the inherited ones so a
337
+ // composed trailer never lands ABOVE one a commit body actually wrote.
338
+ const composedTrailers = (Array.isArray(extraTrailerLines) ? extraTrailerLines : [])
339
+ .filter(Boolean)
340
+ .filter((t) => !present.has(String(t).trim().toLowerCase()) && !inheritedTrailers.some((i) => i.toLowerCase() === String(t).trim().toLowerCase()));
341
+ if (composedTrailers.length) {
342
+ const lastLine = assembled.split('\n').pop().trim();
343
+ assembled += (TRAILER_RE.test(lastLine) ? '\n' : '\n\n') + composedTrailers.join('\n');
344
+ }
345
+
346
+ return spliceCloses(assembled, closes, refs, conflicts);
347
+ }
348
+
349
+ /**
350
+ * Insert an issue-reference paragraph directly under the subject: `Closes #N` for issues the branch
351
+ * completes, `Refs #N` for long-lived memory/tracking issues it touched but must NOT close (#48).
352
+ * Each number is skipped if the message already references it that way.
353
+ *
354
+ * Never append: a message whose last paragraph is a trailer block (`Co-Authored-By:`,
355
+ * `Claude-Session:`) is the normal case, and gluing ` — Closes #N` onto the end corrupts the final
356
+ * trailer's VALUE. GitHub still auto-closes, so nothing fails loudly — but a `Claude-Session:` URL
357
+ * with text welded to it no longer resolves, and the commit is immutable once pushed.
358
+ *
359
+ * `refs` wins over `closes` for a number named in both — a tracking issue must never be closed,
360
+ * even if it was also passed on the close path. The two lists therefore ship disjoint.
361
+ *
362
+ * One thing this pure layer CANNOT do: if a carried commit body literally says `Closes #N` for a
363
+ * number in `refs`, GitHub will still close it on merge — adding `Refs #N` does not un-close it.
364
+ * `colab ship` detects that after the push (the ref issue reads CLOSED) and warns; here we simply
365
+ * do not emit a redundant `Refs #N` when a `Closes #N` for it already sits in the text.
366
+ *
367
+ * The mirror case — an inherited `Refs #N` for a number THIS call closes — is not a limitation the
368
+ * same way: nothing here needs GitHub to un-do anything, so it is reconciled up front by
369
+ * `reconcileClosesRefsConflict` (#58) rather than left for ship to warn about after the fact.
370
+ *
371
+ * Exported so every caller composes the same way. The composed path always did this correctly; the
372
+ * `--message` override concatenated instead, which is exactly the drift a shared helper prevents.
373
+ *
374
+ * @param {string} message
375
+ * @param {Array<number|string>} closes
376
+ * @param {Array<number|string>} refs
377
+ * @param {Array} [conflicts] see `reconcileClosesRefsConflict` — passed straight through
378
+ */
379
+ /**
380
+ * Every issue number `message` carries a closing directive for (`Closes #N` / `closes #N`), as
381
+ * strings, de-duplicated. THE single recogniser for "this text closes #N" — `spliceCloses` uses
382
+ * it to decide what still needs ADDING (#119), and `shipguard.closesCoverage` uses the identical
383
+ * function to decide what is MISSING from the final message. Sharing it is the point: a second,
384
+ * independently-written regex is exactly the drift that would let the composer and the guard
385
+ * disagree about a message they are both looking at.
386
+ *
387
+ * Deliberately narrow, matching `spliceCloses`'s own recognition rule: `Closes` only, not `Fixes` /
388
+ * `Resolves` / `Fixed` / an `owner/repo#N` form — those are GitHub's closing vocabulary, not this
389
+ * repo's, and widening it would change what `spliceCloses` treats as "already present" (out of
390
+ * scope for #119).
391
+ */
392
+ function closedIssueNumbers(message) {
393
+ const out = new Set();
394
+ const re = /[Cc]loses #(\d+)\b/g;
395
+ let m;
396
+ while ((m = re.exec(String(message || '')))) out.add(m[1]);
397
+ return [...out];
398
+ }
399
+
400
+ /**
401
+ * The full GitHub closing-keyword vocabulary, deliberately WIDER than `closedIssueNumbers` above
402
+ * (which matches only this repo's own composed `Closes #N`, on purpose — see its doc comment).
403
+ * This one exists to answer a different question: not "did WE write a closing trailer", but "will
404
+ * GITHUB read this text as one", because GitHub honours the full keyword set inside ANY commit
405
+ * text on the default branch, not just a trailer line this tool composed.
406
+ *
407
+ * #178: `\s*:?\s*` between the keyword and the `#` — not the earlier bare `\s+` — because GitHub
408
+ * accepts an optional colon and does not require whitespace on either side of it: `Closes: #58`,
409
+ * `Closes:#58`, and the original whitespace-only `Closes #58` all read as the same closing
410
+ * reference to GitHub, and this scan's whole job is to answer "will GitHub read this text as one",
411
+ * not "does it match the one shape this repo happens to compose".
412
+ *
413
+ * DELIBERATELY NOT chased here — a wider scan than the keyword-plus-issue-number shape above:
414
+ * - the full-URL form (`closes https://github.com/owner/repo/issues/58`) — documented GitHub
415
+ * behaviour, so a message carrying it is a genuine miss, not a false negative by design;
416
+ * - `GH-58` (GitHub's short cross-reference token);
417
+ * - `owner/repo#58` (cross-repo reference).
418
+ * All three are real gaps, not oversights, and HELP_SHIP says so rather than claiming coverage
419
+ * this scan does not have. The B4 post-push check (`tools/colab`, "did not auto-close") is the
420
+ * backstop under exactly these three shapes — the only one of the two catches (pre-push refusal
421
+ * here, post-push warning there) still reachable once a message carrying one of them has landed.
422
+ */
423
+ const CLOSING_KEYWORD_RE = /\b(close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)\s*:?\s*#(\d+)\b/gi;
424
+
425
+ /**
426
+ * #149: does `message` carry a GitHub closing keyword pointing at an issue `--refs` is keeping
427
+ * open?
428
+ *
429
+ * The gap this closes: `reconcileClosesRefsConflict` above only rewrites a self-contained
430
+ * `Closes #N` / `Refs #N` LINE — the shape ship's own composer produces. It has no opinion on a
431
+ * closing keyword sitting inside ordinary prose, because rewriting inside a sentence is not a safe
432
+ * mechanical operation (same reasoning as `REF_LINE_RE`'s doc comment). But GitHub does not care
433
+ * that the text is prose: `close #58` inside a carried commit SUBJECT ("docs: document X, close #58
434
+ * half 1's deferred note") auto-closes #58 on merge exactly as a trailer would, and #149 needed
435
+ * exactly this — a bullet built from a non-chosen commit's subject, which is squash body content by
436
+ * design (composeSquashMessage's doc comment above).
437
+ *
438
+ * Called BEFORE the push, on the exact string about to be committed — the composed message already
439
+ * exists at that point (spliceCloses / composeSquashMessage have both run), so this is knowable
440
+ * without any new git I/O. The caller decides what to do with a hit; this module stays pure and
441
+ * only reports.
442
+ *
443
+ * WHY BEFORE THE PUSH SPECIFICALLY, not just a clearer post-push message: the commit prose that
444
+ * triggers a wrong close is IMMUTABLE from the moment it lands on the default branch. GitHub's own
445
+ * close can be undone by a human reopening the tracker issue by hand, but the text that caused it
446
+ * cannot — it is now permanent in trunk's history, and every future read of it re-raises the same
447
+ * warning with nothing left to fix. A pre-push refusal and a post-push warning are not two
448
+ * severities of the same fix; only one of them is reachable while the mistake is still reversible.
449
+ *
450
+ * Deliberately checked against `refsIssues` only, not `closeIssues`: a closing keyword hitting a
451
+ * number ship already intends to CLOSE is not a conflict, it is redundant and harmless. It is only
452
+ * a conflict where the flag's entire purpose — keeping the issue open — is being undone by text the
453
+ * flag has no power to edit.
454
+ *
455
+ * @param {string} message
456
+ * @param {Array<number|string>} refsIssues issue numbers this ship keeps OPEN (`--refs`)
457
+ * @returns {Array<{num:string, keyword:string}>} one entry per DISTINCT (num, keyword) hit
458
+ */
459
+ function inheritedClosingKeywordConflicts(message, refsIssues) {
460
+ const refSet = new Set((Array.isArray(refsIssues) ? refsIssues : []).map((n) => String(n).replace(/^#/, '')));
461
+ if (!refSet.size) return [];
462
+ const seen = new Set();
463
+ const out = [];
464
+ let m;
465
+ CLOSING_KEYWORD_RE.lastIndex = 0;
466
+ while ((m = CLOSING_KEYWORD_RE.exec(String(message || '')))) {
467
+ const num = m[2];
468
+ if (!refSet.has(num)) continue;
469
+ const keyword = m[1];
470
+ const key = `${num}:${keyword.toLowerCase()}`;
471
+ if (seen.has(key)) continue;
472
+ seen.add(key);
473
+ out.push({ num, keyword });
474
+ }
475
+ return out;
476
+ }
477
+
478
+ function spliceCloses(message, closes = [], refs = [], conflicts) {
479
+ const norm = (arr) => (arr || []).map((n) => String(n).replace(/^#/, '')).filter(Boolean);
480
+ const refNums = norm(refs);
481
+ const refSet = new Set(refNums);
482
+ const closeNums = norm(closes).filter((n) => !refSet.has(n)); // refs wins — a tracking issue is never closed
483
+
484
+ // Drop any inherited `Refs #N` the branch wrote for an issue THIS call is about to close, before
485
+ // deciding what still needs adding — otherwise the stale trailer survives verbatim alongside the
486
+ // freshly composed `Closes #N` (#58).
487
+ const text = reconcileClosesRefsConflict(message, closeNums, conflicts);
488
+
489
+ const closedAlready = new Set(closedIssueNumbers(text));
490
+ const missingCloses = closeNums
491
+ .filter((n) => !closedAlready.has(n));
492
+ const missingRefs = refNums
493
+ // Skip a ref already referenced. Also skip one the message already CLOSES: this layer only adds
494
+ // text, so it cannot un-close it — ship warns after the push instead of us emitting both keywords.
495
+ .filter((n) => !new RegExp(`[Rr]efs #${n}\\b`).test(text) && !new RegExp(`[Cc]loses #${n}\\b`).test(text));
496
+
497
+ const parts = [
498
+ ...missingCloses.map((n) => `Closes #${n}`),
499
+ ...missingRefs.map((n) => `Refs #${n}`),
500
+ ];
501
+ if (!parts.length) return text;
502
+
503
+ const refLine = parts.join(', ');
504
+ const nl = text.indexOf('\n');
505
+ const head = nl === -1 ? text : text.slice(0, nl);
506
+ const rest = nl === -1 ? '' : text.slice(nl + 1).replace(/^\n+/, '');
507
+ return rest ? `${head}\n\n${refLine}\n\n${rest}` : `${head}\n\n${refLine}`;
508
+ }
509
+
510
+ module.exports = {
511
+ TYPE_WEIGHT, UNRECOGNISED_WEIGHT, BREAKING_BONUS, TRAILER_RE,
512
+ isSyncNoise, parseSubject, commitWeight, hasRecognisedType, unweightedCommits, pickSubjectIndex,
513
+ harvestTrailers, composeSquashMessage, spliceCloses, reconcileClosesRefsConflict,
514
+ closedIssueNumbers, inheritedClosingKeywordConflicts,
515
+ };
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+ /**
3
+ * Does the branch's CI verdict cover the CURRENT base? (#395)
4
+ *
5
+ * A serial `colab ship` used to read only the base's own run (`shipCiCheck`) and then sync the
6
+ * base into the branch locally (B0) and squash — without the synced head ever running. So a
7
+ * branch whose green run was measured on a head cut before the base moved landed on that older
8
+ * verdict whenever the merge was textually clean. Measured: two branches, each green alone, one
9
+ * changing a shared test base class the other's new tests also relied on — the combination went
10
+ * red on trunk and neither run had seen it.
11
+ *
12
+ * The rule: when the branch HAS a CI run at its pushed head, that head must CONTAIN the base's
13
+ * current tip. If it does not, the verdict is `stale-base` — the fix is mechanical (B0: sync the
14
+ * base in, push, wait on the new run, re-ship), so the class is self-clearing, not human-gated.
15
+ *
16
+ * Deliberately NOT built (#395's "optional cheapness"): skipping the re-run when the base commits
17
+ * since the branch's cut touch no file the branch's tests import. What a suite imports is not
18
+ * measurable generically from git, and the issue forbids guessing it — so every stale head re-runs.
19
+ *
20
+ * Pure: every fact is measured by tools/colab (`shipStaleBaseCheck`) and handed in.
21
+ *
22
+ * @param {object} a
23
+ * @param {string|null} a.headSha - the branch's head ON THE REMOTE (what CI runs), null = not pushed
24
+ * @param {object|null} a.run - ghRunForCommit's summary at headSha; null = the read failed
25
+ * @param {string|null} a.baseTip - the base's current tip sha (remote-tracking, freshly fetched)
26
+ * @param {boolean|string|null} a.contains - is baseTip an ancestor of headSha? null = unmeasurable;
27
+ * 'no-change' = it is not, but the head lands no change (evidence-close)
28
+ * @param {number|null} a.behind - commits on the base the head lacks (display only)
29
+ * @param {string} a.base - the base's name, for the detail line
30
+ * @param {boolean} a.ghUsable - false = gh not usable here
31
+ * @returns {{ok:boolean, verdict:string, selfClearing:boolean, detail:string}}
32
+ */
33
+ function staleBaseVerdict(a) {
34
+ const short = (s) => (s ? String(s).slice(0, 7) : '?');
35
+ if (!a.headSha) {
36
+ return { ok: true, verdict: 'no-run', selfClearing: false,
37
+ detail: 'branch not on the remote — no branch run exists to be stale (B2a reads the trunk run at the squash)' };
38
+ }
39
+ if (!a.ghUsable) {
40
+ // The base-CI row already refuses without gh; this row does not add a second, different refusal.
41
+ return { ok: true, verdict: 'unread', selfClearing: false, detail: 'gh not usable — branch run unread (the CI row above already refuses)' };
42
+ }
43
+ if (a.run === null || a.run === undefined) {
44
+ return { ok: false, verdict: 'unread', selfClearing: true,
45
+ detail: `could not read the branch's runs at ${short(a.headSha)} — a failed read is never fresh; re-run` };
46
+ }
47
+ if (a.run.status === 'none') {
48
+ return { ok: true, verdict: 'no-run', selfClearing: false,
49
+ detail: `no branch run at ${short(a.headSha)} — nothing to be stale (Branch CI \`none\`; B2a reads the trunk run at the squash)` };
50
+ }
51
+ if (!a.baseTip || a.contains === null || a.contains === undefined) {
52
+ return { ok: false, verdict: 'unread', selfClearing: true,
53
+ detail: `could not tell whether ${short(a.headSha)} contains ${a.base}'s tip — fetch and re-run` };
54
+ }
55
+ if (a.contains === 'no-change') {
56
+ return { ok: true, verdict: 'no-change', selfClearing: false,
57
+ detail: `the head introduces no change against ${a.base} — nothing lands, so nothing is graded (evidence-close, #90)` };
58
+ }
59
+ if (a.contains) {
60
+ return { ok: true, verdict: 'fresh', selfClearing: false,
61
+ detail: `branch run at ${short(a.headSha)} contains ${a.base}@${short(a.baseTip)}` };
62
+ }
63
+ const n = Number.isFinite(a.behind) ? `${a.behind} commit(s)` : 'commits';
64
+ return { ok: false, verdict: 'stale-base', selfClearing: true,
65
+ detail: `stale-base: the branch run at ${short(a.headSha)} was measured without ${n} now on ${a.base} ` +
66
+ `(tip ${short(a.baseTip)}) — two green runs can combine red. Sync ${a.base} into the branch (B0), ` +
67
+ 'push, wait on the new run (15-minute bound), then re-run ship' };
68
+ }
69
+
70
+ module.exports = { staleBaseVerdict };