@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,358 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/release-policy.js — the `release:` block of `.github/project.yml` (#337, #421).
4
+ *
5
+ * CONVENTIONS.md §6's release routes (#420, superseding the #330 rung) decide, from `exposure` +
6
+ * `deploy`, whether candidate tags are cut automatically and whether a candidate's final tag is
7
+ * automatic. This module is the one executable version of that table, plus the block a repo may
8
+ * declare to CHOOSE a route its row permits and to NARROW it:
9
+ *
10
+ * release:
11
+ * route: public-tool # none | rapid-app | public-tool | library-fast | deploy-tag | live
12
+ * candidates: auto # auto | off
13
+ * candidates-per-day: 1 # positive integer — an opt-in cap; no route has one by default (#443)
14
+ * test-period: 3d # <N>d, never below the route's 3 days
15
+ * final: auto # auto | human
16
+ * guard-run: <command> # #422 — a breaking-change detector `release cut --auto` runs
17
+ * guard-result: <path> # #422 — or the file an earlier CI step wrote its result to
18
+ * exports: <path> # #422 — a committed list of public symbols, one per line
19
+ * npm: <dir> # #433 — publish this package directory to npm from release-auto.yml
20
+ * npm-gate: <command> # #433 — the pack-allowlist gate, run before every npm publish
21
+ * version-source: tag # #438 — tag | manifest: is a manifest's version checked, or derivable?
22
+ * final-grant: 123 # #441 — an operator's recorded decision letting deploy-tag's final be automatic
23
+ *
24
+ * Two layers. The descriptor's ROW (exposure + deploy + production) is a fact about the repo; the
25
+ * ROUTE is how releases run on it. A row permits a fixed set of routes (ROW_ROUTES) and derives one
26
+ * when `route:` is absent. A declared route outside its row's set — `public-tool` on a repo whose
27
+ * tag deploys production, `deploy-tag` on one where nothing deploys — is a FAILURE: the route would
28
+ * misdescribe the repo, and on a deploying tag would hand its final to a machine.
29
+ *
30
+ * The narrowing keys may narrow the route, never widen it. `final: auto` where the route says
31
+ * human, `candidates: auto` where it cuts none, a test period shorter than the route's and more
32
+ * candidates per day than its cap are validation FAILURES, not overrides — "nothing in project.yml
33
+ * lowers that" (§6) is enforced here, not promised.
34
+ *
35
+ * Shared by `audit/audit.mjs` (ESM, through createRequire — the exposure-shape.js precedent) and,
36
+ * later, `colab release cut` (#338). One reading of the rung, not two: a CLI that cut a tag the
37
+ * audit would have called a widening is exactly the two-places drift this repo exists to kill.
38
+ *
39
+ * Fail closed: anything the routes table does not name (undeclared or unknown exposure, a bare
40
+ * legacy `tier: B`, a `released` repo whose deploy/production match no row) derives no route,
41
+ * `candidates: off` + `final: human`, and permits only `route: none` — so no declaration can
42
+ * widen it into automatic tagging.
43
+ */
44
+
45
+ const axisAuthority = require('./axis-authority.js');
46
+
47
+ const KEYS = Object.freeze(['route', 'candidates', 'candidates-per-day', 'test-period', 'final', 'guard-run', 'guard-result', 'exports', 'npm', 'npm-gate', 'version-source', 'final-grant']);
48
+ // #438: where the version a tag names comes from. `manifest` (the default) — every declared manifest
49
+ // (VERSION, package.json, Cargo.toml, pyproject.toml) must already equal the tag, so a human bumps it
50
+ // on trunk first. `tag` — the tag is the version and the manifests are DERIVABLE: the pre-tag check
51
+ // skips them, and the repo's own release/deploy step stamps the number from the tag (on a deploy-only
52
+ // ref or at build time — never a commit on trunk). Neither widens nor narrows a route: it decides
53
+ // which file is the source of a number, never whether a tag is cut.
54
+ const VERSION_SOURCES = Object.freeze(['manifest', 'tag']);
55
+ // #441: the one route whose final may become automatic by an operator's grant, and the row it must
56
+ // sit on — `deploy: tag` only. `deploy: manual` stays human: a person runs that deploy anyway.
57
+ const GRANTABLE_ROUTE = 'deploy-tag';
58
+ const GRANTABLE_ROW = 'released-tag';
59
+ // #433: the npm opt-in. `npm` names the package directory release-auto.yml publishes (`.` for the
60
+ // root); `npm-gate` the command that proves the tarball holds only what was meant to ship. They are
61
+ // a pair — a publish with no gate is the stray-local-file leak the gate exists to stop — and they
62
+ // fit only the public-tool route: an app's tag deploys, and a private repo never publishes to
63
+ // public npm (#432; the workflow refuses that case itself, since visibility is not in this file).
64
+ const NPM_KEYS = Object.freeze(['npm', 'npm-gate']);
65
+ const NPM_ROUTES = Object.freeze(['public-tool']);
66
+ // #422: the bump inputs `release cut --auto` reads. Not a narrowing or a widening — they add evidence
67
+ // to the computed number, never permission — so they only have to be non-empty strings. One of
68
+ // guard-run / guard-result, never both: two detectors answering one question is two readings.
69
+ const INPUT_KEYS = Object.freeze(['guard-run', 'guard-result', 'exports']);
70
+ const CANDIDATES = Object.freeze(['auto', 'off']);
71
+ const FINAL = Object.freeze(['auto', 'human']);
72
+ // The routes' own test period (CONVENTIONS.md §6: "The test period is 3 days"). A floor, not a
73
+ // suggestion: a declared period may be longer, never shorter.
74
+ const TEST_PERIOD_DAYS = 3;
75
+
76
+ /**
77
+ * Each route's own policy — CONVENTIONS.md §6, *Release routes*, row for row.
78
+ * candidates 'auto' | 'off' — are candidate tags vX.Y.Z-rc.N cut automatically?
79
+ * candidatesPerDay number | null — the cap on automatic candidates per day (null = uncapped).
80
+ * Null on every route since #443: the newest candidate always
81
+ * names trunk's head, so a cap is only ever a repo's own narrowing
82
+ * testPeriodDays number | null — a candidate's test period (null = the route has none)
83
+ * final 'auto' | 'human' — is the final vX.Y.Z automatic?
84
+ * finalize how a final is reached: 'none' (no tags), 'after-test-period' (each clean
85
+ * candidate on its own clock), 'newest-clean' (the newest candidate clean for
86
+ * the period; a newer candidate does not restart an older one's clock),
87
+ * 'on-tag' (the tag itself triggers the publish; no candidate), 'human-click'.
88
+ */
89
+ const ROUTE_POLICY = Object.freeze({
90
+ 'none': Object.freeze({ candidates: 'off', candidatesPerDay: null, testPeriodDays: TEST_PERIOD_DAYS, final: 'human', finalize: 'none', why: 'nothing consumes a tag here, so no tags are cut' }),
91
+ 'rapid-app': Object.freeze({ candidates: 'auto', candidatesPerDay: null, testPeriodDays: TEST_PERIOD_DAYS, final: 'auto', finalize: 'newest-clean', why: 'a fast-moving app with few installers: every green trunk head gets a candidate, and the newest clean candidate finalizes automatically' }),
92
+ 'public-tool': Object.freeze({ candidates: 'auto', candidatesPerDay: null, testPeriodDays: TEST_PERIOD_DAYS, final: 'auto', finalize: 'after-test-period', why: 'adopters install it and nothing deploys: every green trunk head gets a candidate, and the final tag is automatic after a clean test period' }),
93
+ 'library-fast': Object.freeze({ candidates: 'off', candidatesPerDay: null, testPeriodDays: null, final: 'auto', finalize: 'on-tag', why: 'a library released per merge and pinned by its consumers: no candidates, the tag triggers the publish and the route\'s checks still apply' }),
94
+ 'deploy-tag': Object.freeze({ candidates: 'auto', candidatesPerDay: null, testPeriodDays: TEST_PERIOD_DAYS, final: 'human', finalize: 'human-click', why: 'the tag deploys production, so the final tag is a human act' }),
95
+ 'live': Object.freeze({ candidates: 'off', candidatesPerDay: null, testPeriodDays: TEST_PERIOD_DAYS, final: 'human', finalize: 'none', why: 'the promotion is the deploy and stays human; no automatic tags' }),
96
+ });
97
+ const ROUTES = Object.freeze(Object.keys(ROUTE_POLICY));
98
+
99
+ /**
100
+ * Which routes each descriptor row permits — the first is the one derived when `route:` is
101
+ * absent. `none` is permitted everywhere: turning releases off is always a narrowing. An
102
+ * `unmatched` row derives no route at all (fail closed) and permits only `none`.
103
+ */
104
+ const ROW_ROUTES = Object.freeze({
105
+ 'no-tags': Object.freeze(['none']),
106
+ 'live': Object.freeze(['live', 'none']),
107
+ 'released-no-production': Object.freeze(['public-tool', 'rapid-app', 'library-fast', 'none']),
108
+ 'released-tag': Object.freeze(['deploy-tag', 'none']),
109
+ 'released-manual': Object.freeze(['deploy-tag', 'none']),
110
+ 'unmatched': Object.freeze(['none']),
111
+ });
112
+
113
+ /**
114
+ * The rung row `cfg` (a parsed project.yml, possibly null) falls on, and the policy it derives.
115
+ * Returns { row, route, axis, candidates, candidatesPerDay, testPeriodDays, final, finalize, why }
116
+ * where `row` is one of 'no-tags' | 'live' | 'released-no-production' | 'released-tag' |
117
+ * 'released-manual' | 'unmatched', `route` is the route that row derives (null on 'unmatched' —
118
+ * fail closed), `axis` is a human label for the finding text, and `why` says what the row means.
119
+ * The policy fields are the derived route's own; `deploy: manual` takes `deploy-tag` because a
120
+ * person deploys from that tag — §6's one human gate covers both.
121
+ */
122
+ function deriveDefault(cfg) {
123
+ const c = cfg || {};
124
+ const rec = axisAuthority.axisOfRecord(c);
125
+ const exposure = rec.exposure;
126
+ const axis = rec.source === 'tier-legacy'
127
+ ? `tier: ${rec.tier} (read as exposure: ${exposure === null ? 'undeclared' : exposure})`
128
+ : rec.source === 'exposure' ? `exposure: ${exposure}` : 'no exposure or tier';
129
+ const deploy = c.deploy === undefined || c.deploy === null ? 'none' : c.deploy;
130
+ const production = c.production === undefined || c.production === '' ? null : c.production;
131
+ const onRoute = (row, why) => {
132
+ const route = ROW_ROUTES[row][0];
133
+ const { why: _routeWhy, ...p } = ROUTE_POLICY[route];
134
+ return { axis, row, route, ...p, why: why || ROUTE_POLICY[route].why };
135
+ };
136
+
137
+ if (exposure === 'none' || exposure === 'self') return onRoute('no-tags');
138
+ if (exposure === 'live') return onRoute('live');
139
+ if (exposure === 'released') {
140
+ if (deploy === 'tag') return onRoute('released-tag');
141
+ if (deploy === 'manual') return onRoute('released-manual', 'a person deploys from the tag, so the final tag is a human act');
142
+ if (deploy === 'none' && production === null) return onRoute('released-no-production');
143
+ }
144
+ return {
145
+ axis, row: 'unmatched', route: null,
146
+ candidates: 'off', candidatesPerDay: null, testPeriodDays: TEST_PERIOD_DAYS, final: 'human', finalize: 'none',
147
+ why: 'no release route names this descriptor, so it fails closed — a human tags',
148
+ };
149
+ }
150
+
151
+ /** A route's policy as an effective-shaped object (no `why`). */
152
+ function routePolicy(route) {
153
+ const p = ROUTE_POLICY[route];
154
+ return p ? { route, candidates: p.candidates, candidatesPerDay: p.candidatesPerDay, testPeriodDays: p.testPeriodDays, final: p.final, finalize: p.finalize, npm: null, versionSource: 'manifest', finalGrant: null } : null;
155
+ }
156
+
157
+ function parseTestPeriod(v) {
158
+ const m = typeof v === 'string' ? /^([0-9]+)d$/.exec(v.trim()) : null;
159
+ return m ? parseInt(m[1], 10) : null;
160
+ }
161
+
162
+ /**
163
+ * Validate the declared `release:` block against the derived default.
164
+ * Returns { declared, derived, effective, findings } — `declared` is the raw block (null when
165
+ * absent), `effective` is what a tool acts on: { route, candidates, candidatesPerDay,
166
+ * testPeriodDays, final, finalize, npm } — the declared route when its row permits it, else the
167
+ * derived one, narrowed by every VALID declared key. An invalid or widening key never reaches
168
+ * `effective`; it is a finding instead. `findings` are { level: 'fail', text } — every problem
169
+ * here is a failure: a block that could widen silently would make the routes a suggestion.
170
+ * `effective.npm` is `{ dir, gate }` only when the npm pair is declared, valid, and on a route that
171
+ * may publish (#433) — anything short of that is null, so the workflow publishes nothing.
172
+ */
173
+ function evaluateRelease(cfg) {
174
+ const c = cfg || {};
175
+ const derived = deriveDefault(c);
176
+ const fromDerived = () => ({
177
+ route: derived.route, candidates: derived.candidates, candidatesPerDay: derived.candidatesPerDay,
178
+ testPeriodDays: derived.testPeriodDays, final: derived.final, finalize: derived.finalize, npm: null,
179
+ versionSource: 'manifest', finalGrant: null,
180
+ });
181
+ let effective = fromDerived();
182
+ const findings = [];
183
+ const fail = (text) => findings.push({ level: 'fail', text });
184
+ const raw = Object.prototype.hasOwnProperty.call(c, 'release') ? c.release : undefined;
185
+
186
+ // Absent, or an empty `release:` with nothing under it — both mean the default.
187
+ if (raw === undefined || raw === null) return { declared: null, derived, effective, findings };
188
+
189
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
190
+ fail(`release is ${JSON.stringify(raw)}, expected a block of ${KEYS.join(' / ')} (omit it for the default ${derived.axis} derives)`);
191
+ return { declared: raw, derived, effective, findings };
192
+ }
193
+
194
+ const routes = 'CONVENTIONS.md §6, Release routes';
195
+ for (const key of Object.keys(raw)) {
196
+ if (!KEYS.includes(key)) fail(`release.${key} is not a release: key — expected one of: ${KEYS.join(', ')}`);
197
+ }
198
+
199
+ for (const key of INPUT_KEYS) {
200
+ if (key in raw && (typeof raw[key] !== 'string' || !raw[key].trim())) fail(`release.${key} is ${JSON.stringify(raw[key])}, expected a non-empty string`);
201
+ }
202
+ for (const key of NPM_KEYS) {
203
+ if (key in raw && (typeof raw[key] !== 'string' || !raw[key].trim())) fail(`release.${key} is ${JSON.stringify(raw[key])}, expected a non-empty string`);
204
+ }
205
+ if (typeof raw.npm === 'string' && raw.npm.trim()) {
206
+ const dir = raw.npm.trim();
207
+ if (dir.startsWith('/') || dir.split('/').includes('..')) fail(`release.npm is ${JSON.stringify(raw.npm)}, expected a directory inside the repo (\`.\` for the root)`);
208
+ }
209
+ if (('npm' in raw) !== ('npm-gate' in raw)) {
210
+ fail('npm' in raw
211
+ ? 'release.npm is declared without release.npm-gate — every npm publish runs a pack-allowlist gate first, so declare the command that proves the tarball holds only what was meant to ship'
212
+ : 'release.npm-gate is declared without release.npm — there is no package to gate; declare the package directory or remove the key');
213
+ }
214
+ if ('guard-run' in raw && 'guard-result' in raw) fail('release.guard-run and release.guard-result are both declared — one detector answers whether the release breaks, so declare one');
215
+
216
+ // 1. The route — chosen among the ones this descriptor's row permits.
217
+ let why = derived.why;
218
+ if ('route' in raw) {
219
+ const v = raw.route;
220
+ const allowed = ROW_ROUTES[derived.row];
221
+ if (!ROUTES.includes(v)) fail(`release.route is ${JSON.stringify(v)}, expected one of: ${ROUTES.join(', ')}`);
222
+ else if (!allowed.includes(v)) {
223
+ fail(`release.route: ${v} does not fit ${derived.axis} — that descriptor permits ${allowed.join(' or ')} (${routes}). ` +
224
+ 'A route is chosen among the ones exposure + deploy permit; change those first if the repo really changed');
225
+ } else {
226
+ effective = routePolicy(v);
227
+ why = ROUTE_POLICY[v].why;
228
+ }
229
+ }
230
+
231
+ // 2. The narrowing keys — against the route now in effect.
232
+ const route = effective.route === null ? 'no route (fail closed)' : `route ${effective.route}`;
233
+ const widen = (key, value, text) => fail(
234
+ `release.${key}: ${value} widens the release route — on ${derived.axis}, ${route}: ${text} (${routes}). ` +
235
+ 'The release: block may narrow its route, never widen it',
236
+ );
237
+
238
+ if ('candidates' in raw) {
239
+ const v = raw.candidates;
240
+ if (!CANDIDATES.includes(v)) fail(`release.candidates is ${JSON.stringify(v)}, expected "auto" or "off"`);
241
+ else if (v === 'auto' && effective.candidates === 'off') widen('candidates', v, `${why}. Remove the key or set candidates: off`);
242
+ else effective.candidates = v;
243
+ }
244
+
245
+ if ('candidates-per-day' in raw) {
246
+ const v = raw['candidates-per-day'];
247
+ const cap = effective.candidatesPerDay;
248
+ if (!Number.isInteger(v) || v < 1) fail(`release.candidates-per-day is ${JSON.stringify(v)}, expected a positive whole number`);
249
+ else if (effective.candidates === 'off') fail(`release.candidates-per-day: ${v} has nothing to cap — candidates are off on ${route}. Remove the key`);
250
+ else if (cap !== null && v > cap) widen('candidates-per-day', v, `at most ${cap} a day. Set ${cap} or fewer`);
251
+ else effective.candidatesPerDay = v;
252
+ }
253
+
254
+ // #441: the operator's grant. Read before `final`, because only a valid grant lets `final: auto`
255
+ // stand on deploy-tag. Its VALIDITY here is shape and place only — that the decision it names is
256
+ // recorded, by a human, and not reopened is a tracker fact: the audit and `colab release finalize`
257
+ // resolve it (finalGrantVerdict), never this pure reading.
258
+ let grant = null;
259
+ if ('final-grant' in raw) {
260
+ const n = parseGrantIssue(raw['final-grant']);
261
+ if (n === null) fail(`release.final-grant is ${JSON.stringify(raw['final-grant'])}, expected the number of the decision issue that records the operator's ruling (e.g. 123 or "#123")`);
262
+ else if (effective.route !== GRANTABLE_ROUTE || derived.row !== GRANTABLE_ROW) {
263
+ fail(`release.final-grant fits only route ${GRANTABLE_ROUTE} on deploy: tag — ${route} on ${derived.axis} is not that (${routes}). ` +
264
+ (derived.row === 'released-manual' ? 'On deploy: manual a person runs the deploy anyway, so its final stays human' : 'Its final is not a deploying human act, so there is nothing to grant'));
265
+ } else grant = { issue: n };
266
+ }
267
+
268
+ if ('final' in raw) {
269
+ const v = raw.final;
270
+ if (!FINAL.includes(v)) fail(`release.final is ${JSON.stringify(v)}, expected "auto" or "human"`);
271
+ else if (v === 'auto' && effective.final === 'human' && grant) {
272
+ // #441: an automatic final that deploys production — permitted only by the recorded grant.
273
+ effective.final = 'auto';
274
+ effective.finalize = 'after-test-period';
275
+ effective.finalGrant = grant;
276
+ } else if (v === 'auto' && effective.final === 'human') {
277
+ widen('final', v, `${why}. Remove the key or set final: human` +
278
+ (effective.route === GRANTABLE_ROUTE && derived.row === GRANTABLE_ROW
279
+ ? ' — or, if the operator chose an automatic final for this repo, record it (colab decision <N> --record --ruled-by <human>) and name it in release.final-grant: <N>'
280
+ : ''));
281
+ } else {
282
+ if (v === 'human' && effective.final === 'auto') effective.finalize = effective.finalize === 'on-tag' ? 'on-tag' : 'human-click';
283
+ effective.final = v;
284
+ }
285
+ }
286
+
287
+ if ('test-period' in raw) {
288
+ const v = raw['test-period'];
289
+ const days = parseTestPeriod(v);
290
+ if (days === null) fail(`release.test-period is ${JSON.stringify(v)}, expected a whole number of days like "${TEST_PERIOD_DAYS}d"`);
291
+ else if (effective.testPeriodDays === null) fail(`release.test-period: ${v} has no period to set — ${route} finalizes on the tag itself, with no candidate. Remove the key`);
292
+ else if (days < effective.testPeriodDays) {
293
+ widen('test-period', v, `the test period is ${effective.testPeriodDays}d, and a shorter one finalizes a candidate before the route's own window has passed. Set ${effective.testPeriodDays}d or longer`);
294
+ } else effective.testPeriodDays = days;
295
+ }
296
+
297
+ // #438: where the tag's version comes from.
298
+ if ('version-source' in raw) {
299
+ const v = raw['version-source'];
300
+ if (!VERSION_SOURCES.includes(v)) fail(`release.version-source is ${JSON.stringify(v)}, expected "tag" or "manifest"`);
301
+ else effective.versionSource = v;
302
+ }
303
+
304
+ // 3. npm (#433) — only on a route where a tag publishes to adopters and deploys nothing.
305
+ effective.npm = null;
306
+ if ('npm' in raw || 'npm-gate' in raw) {
307
+ if (!NPM_ROUTES.includes(effective.route)) {
308
+ fail(`release.npm publishes to npm, which fits only route ${NPM_ROUTES.join(' / ')} — ${route} is not one (${routes}). ` +
309
+ 'A tag that deploys an app is not a package release; remove the npm keys');
310
+ }
311
+ if (!findings.some((f) => f.text.startsWith('release.npm'))) effective.npm = { dir: raw.npm.trim().replace(/\/+$/, '') || '.', gate: raw['npm-gate'].trim() };
312
+ }
313
+
314
+ return { declared: raw, derived, effective, findings };
315
+ }
316
+
317
+ /** `123`, `"123"` or `"#123"` -> 123; anything else -> null. */
318
+ function parseGrantIssue(v) {
319
+ if (Number.isInteger(v) && v > 0) return v;
320
+ const m = typeof v === 'string' ? /^#?([1-9][0-9]*)$/.exec(v.trim()) : null;
321
+ return m ? Number(m[1]) : null;
322
+ }
323
+
324
+ /**
325
+ * #441: does the decision issue a `release.final-grant` names still carry the operator's ruling?
326
+ * `record` is `gh issue view <N> --json state,labels,comments` (null = the read failed — never a
327
+ * grant). Valid only when the issue carries the `decision-recorded` label (applying it needs write
328
+ * permission) AND a live, trusted `⚖ Decision recorded` comment — one not superseded by a later
329
+ * `↩ Decision reopened` (decision-record.js, the same reading every decision consumer uses). A
330
+ * reopened decision revokes the grant at once. `trust` is trust-humans.js parseTrustHumans() of the
331
+ * repo's project.yml, or absent. Returns { ok, ruledBy, detail }.
332
+ */
333
+ function finalGrantVerdict(record, { issue, trust } = {}) {
334
+ const decisionRecord = require('./decision-record.js');
335
+ const ref = `release.final-grant #${issue}`;
336
+ if (!record) return { ok: false, ruledBy: null, detail: `${ref} could not be read from the tracker — an unread grant is not a grant` };
337
+ const labels = (record.labels || []).map((l) => (l && typeof l === 'object' ? l.name : l));
338
+ const all = decisionRecord.liveDecisions(record.comments);
339
+ const live = decisionRecord.trustedDecisions(record.comments, trust);
340
+ const reopened = (record.comments || []).some((c) => decisionRecord.REOPEN_RE.test(String((c && c.body) || '').trim()));
341
+ if (!live.length) {
342
+ const why = reopened && !all.length ? 'its decision was reopened'
343
+ : all.length ? 'its decision was not recorded by a trusted human'
344
+ : 'it carries no recorded decision (colab decision --record)';
345
+ return { ok: false, ruledBy: null, detail: `${ref} does not grant an automatic final: ${why}. The final tag stays a human act until a human records the ruling again` };
346
+ }
347
+ if (!labels.includes('decision-recorded')) {
348
+ return { ok: false, ruledBy: null, detail: `${ref} has a decision comment but no \`decision-recorded\` label — an interrupted record is not a grant` };
349
+ }
350
+ const d = live[live.length - 1];
351
+ return { ok: true, ruledBy: d.ruledBy, detail: `${ref}: decision recorded, ruled by ${d.ruledBy} (${d.at})` };
352
+ }
353
+
354
+ module.exports = {
355
+ VERSION_SOURCES, GRANTABLE_ROUTE, GRANTABLE_ROW, parseGrantIssue, finalGrantVerdict,
356
+ KEYS, INPUT_KEYS, NPM_KEYS, NPM_ROUTES, CANDIDATES, FINAL, TEST_PERIOD_DAYS, ROUTES, ROUTE_POLICY, ROW_ROUTES,
357
+ deriveDefault, evaluateRelease, parseTestPeriod, routePolicy,
358
+ };
@@ -0,0 +1,225 @@
1
+ 'use strict';
2
+ /**
3
+ * "Which tag is the current release?" — answered ONCE, here (#334).
4
+ *
5
+ * Every tag reader in this toolchain used to resolve it with a bare `git describe --tags --abbrev=0`.
6
+ * That returns the nearest tag of ANY shape, so the moment a release candidate (`v1.3.0-rc.1`) is
7
+ * tagged it silently becomes "the release":
8
+ * - stamp.js `handbookInfo` / `freezeVersion` — every adopter's stamp is compared against the
9
+ * candidate and new copies get stamped with it; `cmpSemver` reads the `-rc.1` suffix as 0, so the
10
+ * candidate even compares EQUAL to the final it precedes.
11
+ * - `colab release-status` — "commits since the last tag" resets at each candidate, hiding the
12
+ * merged-but-unreleased gap (#81) exactly while a candidate is waiting.
13
+ * - `colab release-notes` (default range) — the final's notes cover only commits since the last
14
+ * candidate.
15
+ * - `colab handbookVersion` — same as stamp.js.
16
+ *
17
+ * A pre-release is any tag with a `-` in it — SemVer §9's pre-release separator, and the same shape
18
+ * templates/release-tag.yml (#333) marks as a GitHub pre-release. `--exclude '*-*'` is git's own
19
+ * describe filter (git >= 2.13), so the ancestry walk is unchanged and only the candidates drop out.
20
+ * The cost is stated rather than hidden: a non-SemVer tag that happens to contain `-` (`release-2024`)
21
+ * is excluded too. Handbook-convention repos tag `vX.Y.Z`, so nothing conforming is lost.
22
+ *
23
+ * A caller that legitimately wants the newest candidate (a release ritual choosing what to finalize)
24
+ * asks for it explicitly with `{ includePrerelease: true }` — never by accident, which is what the
25
+ * bare describe did.
26
+ *
27
+ * CommonJS, zero dependencies: required by tools/colab (CJS) and by stamp.js, which audit/audit.mjs
28
+ * pulls in through createRequire — so the audit inherits the same answer without a copy of its own.
29
+ */
30
+
31
+ const { execFileSync } = require('child_process');
32
+
33
+ /** git describe pattern matching every pre-release tag (anything carrying SemVer's `-`). */
34
+ const PRERELEASE_TAG_GLOB = '*-*';
35
+
36
+ /** True when `tag` is a pre-release by the rule above. */
37
+ function isPrereleaseTag(tag) {
38
+ return String(tag).includes('-');
39
+ }
40
+
41
+ /**
42
+ * Arguments for `git describe` that honour the rule. `abbrev: 0` gives the bare tag; `abbrev: null`
43
+ * leaves git's default, which is the long form (`v1.2.0-3-gabc1234`) when `ref` is past the tag —
44
+ * the form stamp.js `freezeVersion` stamps with. `ref` defaults to HEAD.
45
+ */
46
+ function describeArgs({ ref = null, abbrev = 0, includePrerelease = false } = {}) {
47
+ const args = ['describe', '--tags'];
48
+ if (abbrev !== null) args.push(`--abbrev=${abbrev}`);
49
+ if (!includePrerelease) args.push(`--exclude=${PRERELEASE_TAG_GLOB}`);
50
+ if (ref) args.push(ref);
51
+ return args;
52
+ }
53
+
54
+ /**
55
+ * The nearest release tag reachable from `ref` (HEAD by default) in the repo at `root`, or null when
56
+ * there is none (no tags, only candidates, not a repo). Never throws.
57
+ *
58
+ * Nearest by ancestry, same as the describe it replaces — "latest reachable", not "highest SemVer".
59
+ */
60
+ function latestReleaseTag(root, { ref = null, includePrerelease = false } = {}) {
61
+ try {
62
+ const out = execFileSync('git', ['-C', root, ...describeArgs({ ref, abbrev: 0, includePrerelease })], {
63
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
64
+ }).trim();
65
+ return out || null;
66
+ } catch (_) {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ // ---- pre-tag checks (#424) — fail closed before ANY candidate or final -------------------------
72
+ //
73
+ // Learned from a library that releases on every merge and publishes to a registry. Three checks, each
74
+ // with its own named reason, run by `colab release cut` and `colab release finalize` before a tag is
75
+ // created — pure (facts in, verdicts out); the CLI measures:
76
+ //
77
+ // manifest-version the tag equals the version every declared manifest carries
78
+ // on-trunk the tagged commit is an ancestor of trunk; a shallow checkout cannot answer
79
+ // outranks-final the version is strictly greater than the highest final tag, so "latest" never
80
+ // moves backwards
81
+
82
+ const PRE_TAG_CONDITIONS = Object.freeze(['manifest-version', 'on-trunk', 'outranks-final']);
83
+
84
+ /** The manifests read, in this order. A manifest that exists but declares no version is not a declaration. */
85
+ const MANIFESTS = Object.freeze(['VERSION', 'package.json', 'Cargo.toml', 'pyproject.toml']);
86
+
87
+ const SEMVER_RE = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z.-]+))?$/;
88
+
89
+ /** `vX.Y.Z[-pre]` or `X.Y.Z[-pre]` -> { major, minor, patch, pre }, or null. */
90
+ function parseSemver(v) {
91
+ const m = SEMVER_RE.exec(String(v || '').trim());
92
+ return m ? { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), pre: m[4] || null } : null;
93
+ }
94
+
95
+ /** Compare the X.Y.Z cores only (a pre-release suffix is ignored). */
96
+ function compareCore(a, b) {
97
+ return (a.major - b.major) || (a.minor - b.minor) || (a.patch - b.patch);
98
+ }
99
+
100
+ /** The `key = "value"` of one TOML table, or undefined / { dynamic } / { workspace }. Deliberately small: a version line, not a TOML parser. */
101
+ function tomlTableVersion(text, table) {
102
+ const lines = String(text).split(/\r?\n/);
103
+ let inTable = false;
104
+ for (const raw of lines) {
105
+ const line = raw.replace(/#.*$/, '').trim();
106
+ const h = /^\[([^\]]+)\]$/.exec(line);
107
+ if (h) { inTable = h[1].trim() === table; continue; }
108
+ if (!inTable) continue;
109
+ if (/^version\.workspace\s*=\s*true$/.test(line) || /^version\s*=\s*\{\s*workspace\s*=\s*true\s*\}$/.test(line)) return { workspace: true };
110
+ const m = /^version\s*=\s*"([^"]*)"$/.exec(line) || /^version\s*=\s*'([^']*)'$/.exec(line);
111
+ if (m) return { value: m[1] };
112
+ if (/^dynamic\s*=.*["']version["']/.test(line)) return { dynamic: true };
113
+ }
114
+ return undefined;
115
+ }
116
+
117
+ /**
118
+ * Every version the repo's manifests declare, read through `readFile(rel)` (string, or null when the
119
+ * file is absent). Returns [{ file, version } | { file, error } | { file, dynamic: true }]. Absent
120
+ * files and manifests with no version field are omitted — they declare nothing.
121
+ */
122
+ function manifestVersions(readFile) {
123
+ const out = [];
124
+ for (const file of MANIFESTS) {
125
+ const text = readFile(file);
126
+ if (text === null || text === undefined) continue;
127
+ if (file === 'VERSION') {
128
+ const v = String(text).trim();
129
+ if (!v) out.push({ file, error: 'VERSION is empty' });
130
+ else out.push({ file, version: v.replace(/^v/, '') });
131
+ } else if (file === 'package.json') {
132
+ let j;
133
+ try { j = JSON.parse(text); } catch (e) { out.push({ file, error: `package.json does not parse (${e.message})` }); continue; }
134
+ if (j && typeof j.version === 'string') out.push({ file, version: j.version });
135
+ else if (j && j.version !== undefined) out.push({ file, error: `package.json version is ${JSON.stringify(j.version)}, not a string` });
136
+ } else if (file === 'Cargo.toml') {
137
+ const v = tomlTableVersion(text, 'package');
138
+ if (!v) continue;
139
+ if (v.workspace) out.push({ file, error: 'Cargo.toml takes version.workspace = true — the workspace root\'s version is not read here' });
140
+ else out.push({ file, version: v.value });
141
+ } else if (file === 'pyproject.toml') {
142
+ const v = tomlTableVersion(text, 'project') || tomlTableVersion(text, 'tool.poetry');
143
+ if (!v) continue;
144
+ if (v.dynamic) out.push({ file, dynamic: true });
145
+ else out.push({ file, version: v.value });
146
+ }
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /**
152
+ * The three pre-tag checks for `tag` (a candidate `vX.Y.Z-rc.N` or a final `vX.Y.Z`).
153
+ *
154
+ * manifests manifestVersions(...) at the tagged commit, or null when it could not be read
155
+ * ancestry { ok, shallow, detail? } — is the commit an ancestor of `trunk`; shallow = the
156
+ * checkout cannot answer (null = not measured)
157
+ * tags every tag name in the repo — the finals among them are what the version must outrank
158
+ * trunk the trunk name, for the detail text
159
+ * versionSource #438 — 'manifest' (default): every declared manifest must equal the tag. 'tag'
160
+ * (`release.version-source: tag`): the manifests are DERIVABLE — the repo's own
161
+ * release/deploy step stamps them from the tag, never on trunk — so a manifest that
162
+ * differs is skipped and named, not refused. A manifest that cannot be read at all
163
+ * (unparsable package.json, an empty VERSION) still refuses: "derivable" says where
164
+ * a number comes from, not that a broken file is fine.
165
+ *
166
+ * Returns [{ condition, ok, detail }] in PRE_TAG_CONDITIONS order — the manifest-version entry also
167
+ * carries `derivable: [file]` (the manifests skipped as derivable; empty on 'manifest'). Every
168
+ * unknown is a refusal.
169
+ */
170
+ function preTagChecks({ tag, manifests, ancestry, tags, trunk = 'main', versionSource = 'manifest' }) {
171
+ const checks = [];
172
+ const add = (condition, ok, detail, extra) => checks.push({ condition, ok: !!ok, detail, ...(extra || {}) });
173
+ const t = parseSemver(tag);
174
+ const core = t ? `${t.major}.${t.minor}.${t.patch}` : null;
175
+
176
+ // 1. manifest-version
177
+ if (!t) add('manifest-version', false, `${tag} is not a vX.Y.Z tag — nothing to compare a manifest against`);
178
+ else if (manifests === null || manifests === undefined) add('manifest-version', false, 'the manifests could not be read at the tagged commit — an unread version is not a matching one');
179
+ else {
180
+ const accepted = t.pre ? [core, `${core}-${t.pre}`] : [core];
181
+ const fromTag = versionSource === 'tag';
182
+ const bad = [];
183
+ const good = [];
184
+ const derivable = [];
185
+ for (const m of manifests) {
186
+ if (m.error) bad.push(`${m.file}: ${m.error}`);
187
+ else if (m.dynamic) good.push(`${m.file} (dynamic — derived from the tag)`);
188
+ else if (!accepted.includes(String(m.version).replace(/^v/, ''))) {
189
+ if (fromTag) derivable.push(m.file);
190
+ else bad.push(`${m.file} says ${m.version}`);
191
+ } else good.push(`${m.file} ${m.version}`);
192
+ }
193
+ const skipped = derivable.length ? `; derivable (release.version-source: tag — stamped from the tag by the repo's release step, never on trunk): ${derivable.join(', ')}` : '';
194
+ if (bad.length) {
195
+ add('manifest-version', false, fromTag
196
+ ? `the tag ${tag} cannot be checked against a manifest — ${bad.join('; ')}. Derivable or not, a manifest that does not read is fixed on trunk first`
197
+ : `the tag ${tag} does not equal the manifest version — ${bad.join('; ')}. Bump the manifest on trunk first, or declare release.version-source: tag if the release stamps it; a tag that disagrees with what the package says it is publishes a lie`, { derivable });
198
+ } else if (!good.length && !derivable.length) add('manifest-version', true, `no version manifest declared (${MANIFESTS.join(', ')}) — the tag is the version`, { derivable });
199
+ else if (!good.length) add('manifest-version', true, `${tag} is the version${skipped}`, { derivable });
200
+ else add('manifest-version', true, `${tag} matches ${good.join(', ')}${skipped}`, { derivable });
201
+ }
202
+
203
+ // 2. on-trunk
204
+ if (!ancestry) add('on-trunk', false, `ancestry not measured — cannot confirm the commit is on ${trunk}`);
205
+ else if (ancestry.shallow) add('on-trunk', false, `a shallow checkout cannot answer whether the commit is on ${trunk} — fetch full history (fetch-depth: 0) and re-run`);
206
+ else if (!ancestry.ok) add('on-trunk', false, ancestry.detail || `the tagged commit is not an ancestor of ${trunk}`);
207
+ else add('on-trunk', true, ancestry.detail || `the tagged commit is an ancestor of ${trunk}`);
208
+
209
+ // 3. outranks-final
210
+ if (!t) add('outranks-final', false, `${tag} is not a vX.Y.Z tag`);
211
+ else {
212
+ const finals = (tags || []).map((n) => ({ n, v: parseSemver(n) })).filter((x) => x.v && !x.v.pre && /^v/.test(x.n));
213
+ finals.sort((a, b) => compareCore(a.v, b.v));
214
+ const top = finals.length ? finals[finals.length - 1] : null;
215
+ if (!top) add('outranks-final', true, 'no final tag yet — nothing to outrank');
216
+ else if (compareCore(t, top.v) <= 0) add('outranks-final', false, `v${core} does not outrank the latest final ${top.n} — "latest" would move backwards`);
217
+ else add('outranks-final', true, `v${core} > latest final ${top.n}`);
218
+ }
219
+ return checks;
220
+ }
221
+
222
+ module.exports = {
223
+ PRERELEASE_TAG_GLOB, isPrereleaseTag, describeArgs, latestReleaseTag,
224
+ PRE_TAG_CONDITIONS, MANIFESTS, parseSemver, manifestVersions, preTagChecks,
225
+ };