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

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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +309 -3
  3. package/README.vi.md +279 -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 +117 -0
  22. package/templates/release-auto.yml +470 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13746 -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-cut.js +822 -0
  73. package/tools/lib/release-finalize.js +481 -0
  74. package/tools/lib/release-policy.js +358 -0
  75. package/tools/lib/release-tag.js +225 -0
  76. package/tools/lib/ship-batch.js +277 -0
  77. package/tools/lib/ship-roles.js +71 -0
  78. package/tools/lib/ship-target-sync.js +181 -0
  79. package/tools/lib/shipguard.js +317 -0
  80. package/tools/lib/shipped-branch.js +56 -0
  81. package/tools/lib/solo.js +213 -0
  82. package/tools/lib/squash.js +515 -0
  83. package/tools/lib/stale-base.js +70 -0
  84. package/tools/lib/stamp.js +703 -0
  85. package/tools/lib/state.js +262 -0
  86. package/tools/lib/teardown.js +83 -0
  87. package/tools/lib/trust-humans.js +104 -0
  88. package/tools/lib/util.js +98 -0
  89. package/tools/lib/wake.js +188 -0
  90. package/tools/lib/workflow-triggers.js +273 -0
  91. package/tools/lib/writes-authority.js +237 -0
  92. package/tools/lib/yaml.js +101 -0
  93. package/bin/cli.js +0 -3
@@ -0,0 +1,481 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/release-finalize.js — the decision behind `colab release finalize` (#339).
4
+ *
5
+ * `colab release cut` (#338, release-cut.js) makes a CANDIDATE, `vX.Y.Z-rc.N`. This module decides
6
+ * what happens to that candidate next under CONVENTIONS.md §6's release rung: keep testing, stop on
7
+ * a human veto, ask for a new candidate, hand a human the one command, or tag the final.
8
+ *
9
+ * PURE BY CONSTRUCTION, the release-cut.js posture: no git, no network, no `gh`, no clock (`now` is
10
+ * passed in). The CLI in tools/colab is the measuring half.
11
+ *
12
+ * WHERE PER-CANDIDATE STATE LIVES (the contract futurelastic/hangar#125 reads — change it and every
13
+ * consumer breaks, so it is frozen here and documented in tools/README.md, *Release finalize*):
14
+ *
15
+ * - the candidates are the annotated `vX.Y.Z-rc.N` tags on origin that `colab release cut` made
16
+ * (first line of the tag message ends `(colab release cut)`); nothing else stores them;
17
+ * - ONE tracking issue per VERSION, never per candidate: title `release: vX.Y.Z`, body's first
18
+ * line `<!-- colab:release version=vX.Y.Z -->`. Per version because the veto lives on it — a
19
+ * `release-hold` on rc.1's issue must still hold rc.2, and no command may move or remove it;
20
+ * - the veto is the `release-hold` label on that issue (a held, still-open issue of a SUPERSEDED
21
+ * version blocks too — a human's hold is never outlived by a newer version number);
22
+ * - a regression against the candidate is a `blocked_by` edge on that issue
23
+ * (`colab blocked <tracking> --by <regression>`): open -> not finalizable; closed AFTER the test
24
+ * period started -> the fix is not in this candidate, so a new candidate is owed;
25
+ * - the test period starts at max(candidate tag's taggerdate, tracking issue's createdAt), so an
26
+ * issue opened late can never shorten the window a human had to veto in;
27
+ * - events are comments on the issue carrying `<!-- colab:release-event k=v … -->` markers.
28
+ *
29
+ * Nothing else is stored: trunk-green-throughout is re-measured from GitHub's run list on every run.
30
+ *
31
+ * `--auto` (#423) changes WHICH candidate a run judges, nothing else: instead of always the newest
32
+ * one (whose clock a daily cut keeps restarting, so on a repo cutting a candidate every day no
33
+ * candidate ever finished a test period), it walks the open candidates newest-first and finalizes
34
+ * the newest one whose OWN test period has elapsed clean — each candidate on its own clock, a newer
35
+ * candidate never restarting an older one's (openCandidates + pickNewestClean). Trunk-green is then
36
+ * read over that candidate's own window [start, endsAt], so a red run after its window closed is
37
+ * about newer code, not it. The release-hold veto and the regression blocked_by rule are unchanged.
38
+ * On a route whose final is a human act (`deploy-tag`) --auto never tags: it stops at
39
+ * candidate-ready and posts the one command, number pre-filled.
40
+ *
41
+ * Before ANY final, the three #424 pre-tag checks (release-tag.js preTagChecks) are required:
42
+ * manifest-version, on-trunk, outranks-final.
43
+ *
44
+ * ANNOUNCING THE FINAL ON THE ISSUES IT CARRIES (#426). For a repo others install, merged is not
45
+ * delivered: the reporter of a fixed bug needs to know which VERSION has the fix. Once a final is
46
+ * tagged, every issue the version carries gets one comment, `Released in vX.Y.Z`. "Carries" is read
47
+ * from git, not from the tracker: every commit in (previous final, the final's commit] whose message
48
+ * holds a GitHub closing keyword (`Closes #N`, `Fixes #N`, … — the vocabulary GitHub itself honours,
49
+ * the same one lib/squash.js CLOSING_KEYWORD_RE scans) — i.e. exactly the issues trunk closed. Each
50
+ * comment carries `<!-- colab:release-event released=vX.Y.Z -->`, so a re-run (or the `already-final`
51
+ * resume after a run died between the tag push and the comments) posts nothing twice. With no
52
+ * previous final there is no lower bound; the first version announces nothing rather than every
53
+ * issue the repo ever closed.
54
+ */
55
+
56
+ const releaseTag = require('./release-tag');
57
+
58
+ const VERSION_RE = /^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
59
+ const CANDIDATE_RE = /^(v(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*))-rc\.([1-9][0-9]*)$/;
60
+ const CUT_SUBJECT_SUFFIX = '(colab release cut)';
61
+ const HOLD_LABEL = 'release-hold';
62
+
63
+ const STATES = Object.freeze([
64
+ 'no-candidate', 'already-final', 'testing', 'held', 'needs-new-candidate', 'refused', 'candidate-ready', 'finalized',
65
+ ]);
66
+
67
+ const CONDITIONS = Object.freeze([
68
+ 'release-policy', 'candidate', 'tracking-issue', 'release-hold', 'regressions', 'test-period', 'trunk-green',
69
+ 'ci-green', 'full-suite', 'schema-additive', 'switch-dependencies',
70
+ ...releaseTag.PRE_TAG_CONDITIONS, 'final-grant', 'migration-grant', 'human',
71
+ ]);
72
+
73
+ // A completed run with one of these conclusions does not make trunk red.
74
+ const NOT_RED = new Set(['success', 'skipped', 'neutral']);
75
+
76
+ function parseVersion(v) {
77
+ const m = VERSION_RE.exec(String(v || ''));
78
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
79
+ }
80
+
81
+ function compareVersions(a, b) {
82
+ const x = parseVersion(a); const y = parseVersion(b);
83
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
84
+ return 0;
85
+ }
86
+
87
+ /** `vX.Y.Z-rc.N` -> { version, n }, or null. */
88
+ function parseCandidate(tag) {
89
+ const m = CANDIDATE_RE.exec(String(tag || ''));
90
+ return m ? { version: m[1], n: Number(m[2]) } : null;
91
+ }
92
+
93
+ // ---- the tracking issue -------------------------------------------------------------------------
94
+
95
+ const RELEASE_MARKER_RE = /<!--\s*colab:release\s+version=(v[0-9]+\.[0-9]+\.[0-9]+)\s*-->/;
96
+
97
+ /** The version a tracking issue's body declares, or null. Only the marker counts, never the title. */
98
+ function parseReleaseMarker(body) {
99
+ const m = RELEASE_MARKER_RE.exec(String(body || ''));
100
+ return m && parseVersion(m[1]) ? m[1] : null;
101
+ }
102
+
103
+ function releaseMarker(version) { return `<!-- colab:release version=${version} -->`; }
104
+
105
+ /** `<!-- colab:release-event k=v … -->`, keys in the order given. */
106
+ function eventMarker(fields) {
107
+ return `<!-- colab:release-event ${Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ')} -->`;
108
+ }
109
+
110
+ /** True when some comment body already carries exactly this event marker — a re-run posts nothing twice. */
111
+ function hasEvent(comments, fields) {
112
+ const marker = eventMarker(fields);
113
+ return (comments || []).some((c) => String((c && c.body) || '').includes(marker));
114
+ }
115
+
116
+ function trackingTitle(version) { return `release: ${version}`; }
117
+
118
+ /** The body, written once at creation. The candidate is deliberately not in it — the tags record that. */
119
+ function trackingBody({ version, row, final, testPeriodDays }) {
120
+ return [
121
+ releaseMarker(version),
122
+ '',
123
+ `Release tracking record for **${version}** — opened by \`colab release finalize\` (CONVENTIONS.md §6, *The release rung*). A record, not a unit of work: never claimed, never started.`,
124
+ '',
125
+ `- Rung row: \`${row}\` — the final tag is **${final === 'auto' ? `automatic after a clean ${testPeriodDays}-day test period` : 'a human act'}**.`,
126
+ `- **Veto:** add the \`${HOLD_LABEL}\` label. While it is present no final is tagged for this version; only a human removes it.`,
127
+ `- **Regression against a candidate:** \`colab blocked <this issue> --by <regression issue>\`. An open one stops the final; one closed after the test period started means a new candidate is owed, and the test period restarts on it.`,
128
+ '- Candidates are the `' + version + '-rc.N` tags; each one is announced below as it is picked up.',
129
+ ].join('\n') + '\n';
130
+ }
131
+
132
+ // ---- which candidate ----------------------------------------------------------------------------
133
+
134
+ /**
135
+ * `tags` is [{ name, annotated, sha, date, subject, onMain }] for every tag in the repo.
136
+ * `pin` is `--tag`, or null. Returns one of:
137
+ * { kind: 'none', detail }
138
+ * { kind: 'already-final', version, detail }
139
+ * { kind: 'refused', detail }
140
+ * { kind: 'candidate', candidate: { tag, version, n, sha, cutAt }, superseded: [version], detail }
141
+ */
142
+ function selectCandidate(tags, pin, remote = 'origin') {
143
+ const all = tags || [];
144
+ const finals = new Set(all.filter((t) => parseVersion(t.name)).map((t) => t.name));
145
+ const rcs = all.map((t) => ({ t, p: parseCandidate(t.name) })).filter((x) => x.p);
146
+
147
+ if (pin) {
148
+ const p = parseCandidate(pin);
149
+ if (!p) return { kind: 'refused', detail: `--tag ${pin} is not a candidate tag (vX.Y.Z-rc.N)` };
150
+ if (!all.some((t) => t.name === pin)) return { kind: 'refused', detail: `--tag ${pin} does not exist on ${remote}` };
151
+ if (finals.has(p.version)) return { kind: 'already-final', version: p.version, detail: `${p.version} is already a final tag` };
152
+ }
153
+
154
+ const open = rcs.filter((x) => !finals.has(x.p.version));
155
+ if (!open.length) {
156
+ if (pin) return { kind: 'refused', detail: `--tag ${pin} is not an open candidate` };
157
+ const done = rcs.map((x) => x.p.version).sort(compareVersions);
158
+ return done.length
159
+ ? { kind: 'already-final', version: done[done.length - 1], detail: `every candidate's version is already final (newest: ${done[done.length - 1]})` }
160
+ : { kind: 'none', detail: 'no candidate tag (vX.Y.Z-rc.N) whose version is not final yet' };
161
+ }
162
+ open.sort((a, b) => compareVersions(a.p.version, b.p.version) || a.p.n - b.p.n);
163
+ const newest = open[open.length - 1];
164
+ const superseded = [...new Set(open.map((x) => x.p.version).filter((v) => v !== newest.p.version))];
165
+
166
+ if (pin && pin !== newest.t.name) {
167
+ return { kind: 'refused', detail: `--tag ${pin} is not the newest candidate (${newest.t.name}) — a final names the candidate that was actually tested last` };
168
+ }
169
+ const t = newest.t;
170
+ if (!t.annotated || !String(t.subject || '').endsWith(CUT_SUBJECT_SUFFIX)) {
171
+ return { kind: 'refused', detail: `${t.name} was not made by \`colab release cut\` (not an annotated tag whose message ends "${CUT_SUBJECT_SUFFIX}") — a candidate cut by hand is never finalized (CONVENTIONS.md §6)` };
172
+ }
173
+ if (!t.onMain) return { kind: 'refused', detail: `${t.name} (${String(t.sha).slice(0, 7)}) is not on ${remote}/main — candidates are cut from main` };
174
+ if (!t.date || Number.isNaN(Date.parse(t.date))) return { kind: 'refused', detail: `${t.name} has no readable tagger date — the test period cannot be placed` };
175
+
176
+ return {
177
+ kind: 'candidate',
178
+ candidate: { tag: t.name, version: newest.p.version, n: newest.p.n, sha: t.sha, cutAt: new Date(t.date).toISOString() },
179
+ superseded,
180
+ detail: `${t.name} at ${String(t.sha).slice(0, 7)}, cut ${new Date(t.date).toISOString()}${superseded.length ? ` (supersedes ${superseded.join(', ')})` : ''}`,
181
+ };
182
+ }
183
+
184
+ /**
185
+ * --auto (#423): every OPEN candidate, newest first — the walk pickNewestClean takes. Each entry is
186
+ * { tag, version, n, sha, cutAt, refused } where `refused` is null or why this one candidate can never
187
+ * be finalized (hand-made, off main, no tagger date) — it is skipped, never finalized, and reported.
188
+ */
189
+ function openCandidates(tags, remote = 'origin') {
190
+ const all = tags || [];
191
+ const finals = new Set(all.filter((t) => parseVersion(t.name)).map((t) => t.name));
192
+ const open = all.map((t) => ({ t, p: parseCandidate(t.name) })).filter((x) => x.p && !finals.has(x.p.version));
193
+ open.sort((a, b) => compareVersions(b.p.version, a.p.version) || b.p.n - a.p.n);
194
+ return open.map(({ t, p }) => {
195
+ let refused = null;
196
+ if (!t.annotated || !String(t.subject || '').endsWith(CUT_SUBJECT_SUFFIX)) refused = `${t.name} was not made by \`colab release cut\` — a candidate cut by hand is never finalized`;
197
+ else if (!t.onMain) refused = `${t.name} (${String(t.sha).slice(0, 7)}) is not on ${remote}/main`;
198
+ else if (!t.date || Number.isNaN(Date.parse(t.date))) refused = `${t.name} has no readable tagger date — its test period cannot be placed`;
199
+ return { tag: t.name, version: p.version, n: p.n, sha: t.sha, cutAt: refused ? null : new Date(t.date).toISOString(), refused };
200
+ });
201
+ }
202
+
203
+ /**
204
+ * --auto (#423): `evaluations` is [{ candidate, verdict }] NEWEST FIRST, one decide() per candidate
205
+ * judged. Returns { candidate, verdict, skipped: [{ tag, state }] }:
206
+ * - any `held` verdict wins outright — a human veto is never walked around;
207
+ * - else the first `finalized` (the newest candidate clean on its own clock);
208
+ * - else the newest candidate's verdict (testing, refused …), with the older ones listed as skipped.
209
+ */
210
+ function pickNewestClean(evaluations) {
211
+ const ev = evaluations || [];
212
+ if (!ev.length) return { candidate: null, verdict: null, skipped: [] };
213
+ const held = ev.find((e) => e.verdict.state === 'held');
214
+ const pick = held || ev.find((e) => e.verdict.state === 'finalized') || ev[0];
215
+ return { candidate: pick.candidate, verdict: pick.verdict, skipped: ev.filter((e) => e !== pick).map((e) => ({ tag: e.candidate.tag, state: e.verdict.state })) };
216
+ }
217
+
218
+ // ---- the test period ----------------------------------------------------------------------------
219
+
220
+ /** { start, endsAt, elapsed, detail } — start = max(cutAt, trackingCreatedAt). All ISO strings. */
221
+ function periodVerdict({ cutAt, trackingCreatedAt, testPeriodDays, now }) {
222
+ const cut = Date.parse(cutAt);
223
+ const created = trackingCreatedAt ? Date.parse(trackingCreatedAt) : NaN;
224
+ const nowMs = Date.parse(now);
225
+ const startMs = Number.isNaN(created) ? Math.max(cut, nowMs) : Math.max(cut, created);
226
+ const endMs = startMs + testPeriodDays * 86400000;
227
+ const elapsed = nowMs >= endMs;
228
+ const left = Math.max(0, endMs - nowMs);
229
+ const hours = Math.ceil(left / 3600000);
230
+ return {
231
+ start: new Date(startMs).toISOString(),
232
+ endsAt: new Date(endMs).toISOString(),
233
+ elapsed,
234
+ detail: elapsed
235
+ ? `${testPeriodDays}d test period from ${new Date(startMs).toISOString()} ended ${new Date(endMs).toISOString()}`
236
+ : `${testPeriodDays}d test period from ${new Date(startMs).toISOString()} ends ${new Date(endMs).toISOString()} (${hours}h left)`,
237
+ };
238
+ }
239
+
240
+ /**
241
+ * Trunk CI green THROUGHOUT the period. `runs` is `gh run list --branch main` rows (null = unread),
242
+ * `truncated` true when the read hit its limit. Only runs created at/after `periodStart`, of a
243
+ * workflow in `suiteWorkflows` (the workflows that vetted the candidate — an unrelated scheduled
244
+ * workflow cannot veto a release), and not `pull_request` events, count.
245
+ *
246
+ * Returns { ok, permanent, pending, detail }:
247
+ * - a completed run that failed (anything but success/skipped/neutral/cancelled) -> permanent:
248
+ * trunk was red during this candidate's period, and nothing later un-reds it;
249
+ * - cancelled -> fine when a LATER run of the same workflow succeeded or is still running
250
+ * (pending), otherwise not clean (not permanent: a re-run can settle it);
251
+ * - a run still queued/in progress -> pending.
252
+ */
253
+ function trunkGreenVerdict(runs, { periodStart, periodEnd = null, suiteWorkflows, truncated }) {
254
+ if (runs === null || runs === undefined) return { ok: false, permanent: false, pending: false, detail: 'gh run list failed — cannot confirm trunk stayed green' };
255
+ if (truncated) return { ok: false, permanent: false, pending: false, detail: 'the run list hit its read limit — cannot confirm trunk stayed green' };
256
+ const startMs = Date.parse(periodStart);
257
+ // #423: --auto bounds the window to the candidate's own period — a run after it closed is about newer code.
258
+ const endMs = periodEnd ? Date.parse(periodEnd) : Infinity;
259
+ const suite = new Set(suiteWorkflows || []);
260
+ const inWindow = runs.filter((r) => r && Date.parse(r.createdAt) >= startMs && Date.parse(r.createdAt) < endMs && suite.has(r.workflowName || '(unnamed workflow)') && r.event !== 'pull_request');
261
+ const red = inWindow.filter((r) => r.status === 'completed' && !NOT_RED.has(r.conclusion) && r.conclusion !== 'cancelled');
262
+ if (red.length) {
263
+ return { ok: false, permanent: true, pending: false, detail: `trunk went red during the test period: ${red.map((r) => `${r.workflowName} ${r.conclusion} at ${String(r.headSha).slice(0, 7)} (${r.createdAt})`).join('; ')}` };
264
+ }
265
+ const unsettled = [];
266
+ let pending = inWindow.some((r) => r.status !== 'completed');
267
+ for (const c of inWindow.filter((r) => r.status === 'completed' && r.conclusion === 'cancelled')) {
268
+ const later = inWindow.filter((r) => r.workflowName === c.workflowName && Date.parse(r.createdAt) > Date.parse(c.createdAt));
269
+ if (later.some((r) => r.status === 'completed' && r.conclusion === 'success')) continue;
270
+ if (later.some((r) => r.status !== 'completed')) { pending = true; continue; }
271
+ unsettled.push(`${c.workflowName} cancelled at ${String(c.headSha).slice(0, 7)} with no later run`);
272
+ }
273
+ if (unsettled.length) return { ok: false, permanent: false, pending: false, detail: `not settled: ${unsettled.join('; ')}` };
274
+ if (pending) return { ok: false, permanent: false, pending: true, detail: 'a trunk run in the test period is still in flight' };
275
+ return { ok: true, permanent: false, pending: false, detail: `${inWindow.length} trunk run(s) of the candidate's workflows since ${periodStart}${periodEnd ? ` until ${periodEnd}` : ''}, none red` };
276
+ }
277
+
278
+ /**
279
+ * `edges` is the tracking issue's blocked_by list [{ number, state, closedAt }] (null = unread;
280
+ * [] when there is no tracking issue yet). Returns { ok, permanent, detail }.
281
+ */
282
+ function regressionVerdict(edges, { periodStart }) {
283
+ if (edges === null || edges === undefined) return { ok: false, permanent: false, detail: 'the tracking issue\'s blocked_by edges could not be read — an unread regression is not a cleared one' };
284
+ const startMs = Date.parse(periodStart);
285
+ const open = edges.filter((e) => String(e.state).toLowerCase() !== 'closed');
286
+ const closedAfter = edges.filter((e) => String(e.state).toLowerCase() === 'closed' && (!e.closedAt || Date.parse(e.closedAt) >= startMs));
287
+ if (open.length) return { ok: false, permanent: false, detail: `open regression(s) against the candidate: ${open.map((e) => `#${e.number}`).join(', ')}` };
288
+ if (closedAfter.length) {
289
+ return { ok: false, permanent: true, detail: `regression(s) fixed after this candidate's test period began (${closedAfter.map((e) => `#${e.number}`).join(', ')}) — the fix is not in it; a new candidate is owed` };
290
+ }
291
+ return { ok: true, permanent: false, detail: edges.length ? `${edges.length} regression edge(s), all closed before the test period began` : 'no regression recorded against the candidate' };
292
+ }
293
+
294
+ // ---- an operator-granted automatic final (#441) ------------------------------------------------
295
+
296
+ /**
297
+ * On a deploy-tag route whose final the operator granted automatic (release.final-grant), a final
298
+ * that deploys production must not carry a database migration nobody granted: migration stays a
299
+ * human gate. `paths` is every migration file changed since the last final (null = unread);
300
+ * `grant` is migration-grant.js evaluateIssue() of the version's TRACKING issue, bound to the
301
+ * version (`colab migration-grant <tracking> --branch vX.Y.Z`), or null when there was nothing to
302
+ * evaluate. Returns { ok, detail }.
303
+ */
304
+ function migrationGrantVerdict({ paths, grant, since }) {
305
+ if (paths === null || paths === undefined) return { ok: false, detail: 'the migration files since the last final could not be read — an unread migration is not an absent one' };
306
+ if (!paths.length) return { ok: true, detail: `no migration file changed since ${since || 'the first commit'}` };
307
+ const list = paths.join(', ');
308
+ if (grant && grant.ok) return { ok: true, detail: `${paths.length} migration file(s) since ${since || 'the first commit'} (${list}), granted on the tracking issue #${grant.issue}` };
309
+ return {
310
+ ok: false,
311
+ detail: `${paths.length} migration file(s) since ${since || 'the first commit'} (${list}) and no migration grant on the release${grant && grant.reason ? ` (${grant.reason})` : ''} — an automatically deployed final never carries an ungranted migration; a human finalizes, or grants it first (COLAB_HUMAN=1 colab migration-grant <tracking issue> --branch <version>)`,
312
+ };
313
+ }
314
+
315
+ // ---- the verdict --------------------------------------------------------------------------------
316
+
317
+ /** The one command a human runs to finalize — printed and posted, never written into a skill. */
318
+ function handoffCommand(tag) {
319
+ return `COLAB_HUMAN=1 colab release finalize --tag ${tag} --answered-by "<your name>"`;
320
+ }
321
+
322
+ /**
323
+ * `facts`:
324
+ * policy release-policy.js evaluateRelease(doc)
325
+ * selection selectCandidate(...)
326
+ * tracking { number|null, createdAt|null, held, wouldCreate } | { error }
327
+ * supersededHeld [issue numbers]
328
+ * period periodVerdict(...) (when there is a candidate)
329
+ * trunk trunkGreenVerdict(...)
330
+ * regressions regressionVerdict(...)
331
+ * ci, suite, schema, switches { ok, detail }
332
+ * finalGrant #441 — release-policy.js finalGrantVerdict() of policy.effective.finalGrant (only
333
+ * read when the policy carries one; absent = unresolved, never a grant)
334
+ * migrations #441 — migrationGrantVerdict() (only read when the policy carries a grant)
335
+ * human { bar: bool, answeredBy }
336
+ *
337
+ * Returns { state, checks: [{ condition, ok, required, detail }], finalTag, handoff, grant }.
338
+ *
339
+ * #441: where the final is automatic only by an operator's grant (deploy-tag + release.final-grant),
340
+ * the grant must still resolve AND no ungranted migration may ride along. Either one failing does not
341
+ * refuse the release — it takes the automatic final away, so the run stops at candidate-ready and
342
+ * hands a human the one command, exactly as on an ungranted deploy-tag repo. A human running the
343
+ * bar on a granted repo takes the human path too: the grant adds a way to finalize, never removes one.
344
+ * `grant` in the verdict is { issue, ruledBy } when a granted automatic final was reached, else null.
345
+ */
346
+ function decide(facts) {
347
+ const f = facts || {};
348
+ const checks = [];
349
+ const add = (condition, ok, detail, required = true) => checks.push({ condition, ok: !!ok, required, detail });
350
+ const out = (state, extra = {}) => ({ state, checks, finalTag: null, handoff: null, grant: null, ...extra });
351
+
352
+ const p = f.policy;
353
+ const finalMode = p && p.effective ? p.effective.final : 'human';
354
+ const row = p && p.derived ? p.derived.row : 'unmatched';
355
+ if (!p) add('release-policy', false, 'no release policy was evaluated');
356
+ else if (p.findings && p.findings.length) add('release-policy', false, `the release: block is invalid — ${p.findings.map((x) => x.text).join('; ')}`);
357
+ else if (!/^released-/.test(row)) add('release-policy', false, `${p.derived.axis}: ${p.derived.why} — nothing to finalize here (CONVENTIONS.md §6, The release rung)`);
358
+ else add('release-policy', true, `${p.derived.axis} (${row}): final ${finalMode}, test period ${p.effective.testPeriodDays}d`);
359
+ if (!checks[0].ok) return out('refused');
360
+
361
+ const s = f.selection || { kind: 'none', detail: 'no candidate selected' };
362
+ if (s.kind === 'none') { add('candidate', false, s.detail); return out('no-candidate'); }
363
+ if (s.kind === 'already-final') { add('candidate', true, s.detail); return out('already-final', { version: s.version }); }
364
+ if (s.kind !== 'candidate') { add('candidate', false, s.detail); return out('refused'); }
365
+ add('candidate', true, s.detail);
366
+ const cand = s.candidate;
367
+
368
+ const t = f.tracking || {};
369
+ if (t.error) { add('tracking-issue', false, t.error); return out('refused'); }
370
+ add('tracking-issue', true, t.number ? `#${t.number} (${trackingTitle(cand.version)})` : `none yet — ${t.wouldCreate ? 'this run opens' : 'a non-dry run opens'} "${trackingTitle(cand.version)}"`);
371
+
372
+ const held = [...(t.held && t.number ? [t.number] : []), ...(f.supersededHeld || [])];
373
+ add('release-hold', !held.length, held.length
374
+ ? `${HOLD_LABEL} on ${held.map((n) => `#${n}`).join(', ')} — a human veto; not finalized while it is present, and no command removes it`
375
+ : `no ${HOLD_LABEL} on the tracking issue${(f.supersededHeld || []).length ? '' : ' or any superseded open one'}`);
376
+
377
+ const h = f.human || { bar: false };
378
+ // #441: an automatic final that deploys production exists only by the operator's grant.
379
+ const granted = p.effective.finalGrant || null;
380
+ let auto = finalMode === 'auto';
381
+ let grantUsed = null;
382
+ if (granted && auto) {
383
+ const g = f.finalGrant || { ok: false, detail: `release.final-grant #${granted.issue} was not resolved — an unresolved grant is not a grant` };
384
+ add('final-grant', g.ok, `${g.detail}${g.ok ? '' : ' — the final falls back to a human act'}`, false);
385
+ const mig = f.migrations || { ok: false, detail: 'migrations since the last final were not measured' };
386
+ add('migration-grant', mig.ok, `${mig.detail}${mig.ok || !g.ok ? '' : ' — the final falls back to a human act'}`, false);
387
+ if (!g.ok || !mig.ok || h.bar) auto = false;
388
+ else grantUsed = { issue: granted.issue, ruledBy: g.ruledBy || null };
389
+ }
390
+ const reg = f.regressions || { ok: false, permanent: false, detail: 'not measured' };
391
+ add('regressions', reg.ok, reg.detail);
392
+ const per = f.period || { elapsed: false, detail: 'not measured' };
393
+ add('test-period', per.elapsed, per.detail, auto);
394
+ const tr = f.trunk || { ok: false, permanent: false, pending: false, detail: 'not measured' };
395
+ add('trunk-green', tr.ok, tr.detail, auto);
396
+ for (const [condition, v] of [['ci-green', f.ci], ['full-suite', f.suite], ['schema-additive', f.schema], ['switch-dependencies', f.switches]]) {
397
+ add(condition, v && v.ok, v ? v.detail : 'not measured');
398
+ }
399
+ // #424: before any final — the tag equals the manifests, the commit is on trunk, the version outranks the latest final.
400
+ for (const c of releaseTag.preTagChecks({ tag: cand.version, manifests: f.manifests, ancestry: f.ancestry, tags: f.tags, trunk: 'main', versionSource: p.effective.versionSource === 'tag' ? 'tag' : 'manifest' })) add(c.condition, c.ok, c.detail);
401
+ if (!auto) {
402
+ add('human', h.bar, h.bar
403
+ ? `human bar met — answered by ${h.answeredBy}`
404
+ : 'the final tag is a human act on this row: an agent run stops at candidate-ready and hands over the command');
405
+ }
406
+
407
+ if (held.length) return out('held');
408
+ if ((reg.permanent) || (auto && tr.permanent)) return out('needs-new-candidate');
409
+ const blocking = checks.filter((c) => c.required && !c.ok && !['test-period', 'trunk-green', 'human'].includes(c.condition));
410
+ if (blocking.length) return out('refused');
411
+ if (auto) {
412
+ if (!tr.ok && !tr.pending) return out('refused');
413
+ if (!per.elapsed || tr.pending) return out('testing');
414
+ return out('finalized', { finalTag: cand.version, grant: grantUsed });
415
+ }
416
+ if (!h.bar) return out('candidate-ready', { handoff: handoffCommand(cand.tag) });
417
+ return out('finalized', { finalTag: cand.version });
418
+ }
419
+
420
+ // ---- announcing the final (#426) ----------------------------------------------------------------
421
+
422
+ // GitHub's closing-keyword vocabulary — kept identical to lib/squash.js CLOSING_KEYWORD_RE.
423
+ const CARRIED_RE = /\b(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)\s*:?\s*#(\d+)\b/gi;
424
+
425
+ /**
426
+ * The issue numbers a release carries: every closing reference in `messages` (the commit messages in
427
+ * the version's range), deduplicated, ascending, minus `exclude` (the release tracking issues — a
428
+ * record, never something a release "fixes").
429
+ */
430
+ function carriedIssues(messages, { exclude = [] } = {}) {
431
+ const skip = new Set((exclude || []).map(Number));
432
+ const out = new Set();
433
+ for (const msg of messages || []) {
434
+ CARRIED_RE.lastIndex = 0;
435
+ let m;
436
+ while ((m = CARRIED_RE.exec(String(msg || '')))) {
437
+ const n = Number(m[1]);
438
+ if (n > 0 && !skip.has(n)) out.add(n);
439
+ }
440
+ }
441
+ return [...out].sort((a, b) => a - b);
442
+ }
443
+
444
+ /** The highest final tag strictly below `version`, or null — the lower bound of what `version` carries. */
445
+ function previousFinal(tagNames, version) {
446
+ const below = (tagNames || []).filter((t) => parseVersion(t) && compareVersions(t, version) < 0).sort(compareVersions);
447
+ return below.length ? below[below.length - 1] : null;
448
+ }
449
+
450
+ /** The event fields of a "released in" comment — one per issue per version. */
451
+ function releasedEvent(version) { return { released: version }; }
452
+
453
+ /** The comment body posted on each carried issue (marker included). */
454
+ function releasedComment(version, sha) {
455
+ return `${eventMarker(releasedEvent(version))}\nReleased in **${version}** (\`${String(sha || '').slice(0, 7)}\`).`;
456
+ }
457
+
458
+ /** The final tag's annotated message: which candidate, which period, every condition, who. */
459
+ function tagMessage(verdict, { candidate, period, actor }) {
460
+ return [
461
+ `${candidate.version} — release (colab release finalize)`,
462
+ '',
463
+ `Candidate: ${candidate.tag}`,
464
+ `Commit: ${candidate.sha}`,
465
+ period ? `Test period: ${period.start} -> ${period.endsAt}` : null,
466
+ `Finalized by: ${actor}`,
467
+ verdict.grant ? `Automatic final granted by: release.final-grant -> decision #${verdict.grant.issue}${verdict.grant.ruledBy ? `, ruled by ${verdict.grant.ruledBy}` : ''} (an operator's per-repo grant; deleting it, or final: human, revokes it)` : null,
468
+ '',
469
+ 'Conditions (CONVENTIONS.md §6):',
470
+ ...verdict.checks.map((c) => `- ${c.condition}: ${c.ok ? 'ok' : (c.required ? 'FAILED' : 'informational')} — ${c.detail}`),
471
+ ].filter((l) => l !== null).join('\n') + '\n';
472
+ }
473
+
474
+ module.exports = {
475
+ STATES, CONDITIONS, HOLD_LABEL, CUT_SUBJECT_SUFFIX,
476
+ parseVersion, compareVersions, parseCandidate,
477
+ parseReleaseMarker, releaseMarker, eventMarker, hasEvent, trackingTitle, trackingBody,
478
+ selectCandidate, openCandidates, pickNewestClean, periodVerdict, trunkGreenVerdict, regressionVerdict,
479
+ handoffCommand, decide, tagMessage, migrationGrantVerdict,
480
+ carriedIssues, previousFinal, releasedEvent, releasedComment,
481
+ };