@futurelastic/colab-handbook 1.12.0-rc.58 → 1.12.0-rc.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -31,5 +31,5 @@
31
31
  "engines": {
32
32
  "node": ">=18"
33
33
  },
34
- "version": "1.12.0-rc.58"
34
+ "version": "1.12.0-rc.60"
35
35
  }
package/tools/colab CHANGED
@@ -15,6 +15,7 @@ const { spawnSync } = require('child_process');
15
15
 
16
16
  const state = require('./lib/state');
17
17
  const git = require('./lib/git');
18
+ const tracker = require('./lib/tracker'); // every gh call goes through tracker-github.js (#500)
18
19
  const ports = require('./lib/ports');
19
20
  const stamp = require('./lib/stamp');
20
21
  const releaseTag = require('./lib/release-tag');
@@ -1323,16 +1324,13 @@ no-op; 1 when refused.
1323
1324
  function readAllIssuesForSwitches(repoAbs) {
1324
1325
  const LIMIT = 5000;
1325
1326
  // title/labels/createdAt/url are additive (#339): `release finalize` finds its tracking issue in the same read.
1326
- const r = spawnSync('gh', ['issue', 'list', '--state', 'all', '--limit', String(LIMIT), '--json', 'number,state,stateReason,body,title,labels,createdAt,closedAt,url'],
1327
- { cwd: repoAbs, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 });
1328
- if (r.status !== 0) return null;
1329
- try {
1330
- const list = JSON.parse(r.stdout);
1331
- // A full page may be a truncated one — an unread marker is not a cleared one.
1332
- return Array.isArray(list) && list.length < LIMIT ? list : null;
1333
- } catch (_) {
1334
- return null;
1335
- }
1327
+ const r = tracker.forRepo(repoAbs).issueListAll({
1328
+ limit: LIMIT, fields: ['number', 'state', 'stateReason', 'body', 'title', 'labels', 'createdAt', 'closedAt', 'url'],
1329
+ maxBuffer: 512 * 1024 * 1024,
1330
+ });
1331
+ const list = r.data; // null: the read failed or was unparseable
1332
+ // A full page may be a truncated one — an unread marker is not a cleared one.
1333
+ return Array.isArray(list) && list.length < LIMIT ? list : null;
1336
1334
  }
1337
1335
 
1338
1336
  /** [{status, path, content}] for every path changed between `from` (null = the empty tree) and `sha`; null on a git failure. */
@@ -1673,15 +1671,14 @@ function cmdReleaseCut(argv) {
1673
1671
  announced = announceCarried(repoAbs, { tagNames: [...tags, verdict.tag], exclude, version: verdict.tag, sha });
1674
1672
  if (fastFacts.tracking) {
1675
1673
  commentOnce(repoAbs, fastFacts.tracking.number, { state: 'finalized', tag: verdict.tag }, `**${verdict.tag}** tagged final on \`${shortSha(sha)}\` by route deploy-tag-fast — the release workflow deploys it in this run.`);
1676
- const r = spawnSync('gh', ['issue', 'close', String(fastFacts.tracking.number)], { cwd: repoAbs, encoding: 'utf8' });
1677
- if (r.status !== 0) warn(`could not close #${fastFacts.tracking.number}: ${String(r.stderr || '').split('\n')[0]}`);
1674
+ const r = tracker.forRepo(repoAbs).issueClose(fastFacts.tracking.number);
1675
+ if (!r.ok) warn(`could not close #${fastFacts.tracking.number}: ${String(r.stderr || '').split('\n')[0]}`);
1678
1676
  }
1679
1677
  } else if (handoff && verdict.version) {
1680
1678
  let num = fastFacts.tracking ? fastFacts.tracking.number : null;
1681
1679
  if (!num && issues !== null) {
1682
- const c = spawnSync('gh', ['issue', 'create', '--title', releaseFinalize.trackingTitle(verdict.version), '--body', releaseCut.handoffTrackingBody(verdict.version)], { cwd: repoAbs, encoding: 'utf8' });
1683
- const m = c.status === 0 ? /\/issues\/([0-9]+)/.exec(c.stdout || '') : null;
1684
- if (m) num = Number(m[1]);
1680
+ const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(verdict.version), body: releaseCut.handoffTrackingBody(verdict.version) });
1681
+ if (c.number) num = c.number;
1685
1682
  else warn(`could not open the tracking issue for ${verdict.version} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'}) — the hand-off is printed here only`);
1686
1683
  }
1687
1684
  if (num) {
@@ -1757,8 +1754,8 @@ function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false })
1757
1754
  // #446: a deploy-tag-fast final is published as a full release, marked latest.
1758
1755
  const kind = final ? 'release' : 'pre-release';
1759
1756
  if (!isGhUsable(repoAbs)) return { ok: false, detail: `${kind} NOT published: gh not usable (${ghUnusableWhy(repoAbs)})` };
1760
- const view = spawnSync('gh', ['release', 'view', tag, '--json', 'tagName'], { cwd: repoAbs, encoding: 'utf8' });
1761
- if (view.status === 0) return { ok: true, detail: `${tag} already has a GitHub Release — left as it is` };
1757
+ const view = tracker.forRepo(repoAbs).releaseView(tag);
1758
+ if (view.ok) return { ok: true, detail: `${tag} already has a GitHub Release — left as it is` };
1762
1759
  let notes;
1763
1760
  try {
1764
1761
  notes = lastFinal ? buildReleaseNotes(repoAbs, `${lastFinal}..${tag}`, lastFinal).out : `## ${tag}\n\nFirst release.\n`;
@@ -1769,8 +1766,8 @@ function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false })
1769
1766
  const file = path.join(os.tmpdir(), `colab-release-notes-${process.pid}-${tag}.md`);
1770
1767
  fs.writeFileSync(file, notes);
1771
1768
  try {
1772
- const r = spawnSync('gh', final ? releaseCut.finalReleaseArgs(tag, file) : releaseCut.prereleaseArgs(tag, file), { cwd: repoAbs, encoding: 'utf8' });
1773
- if (r.status !== 0) return { ok: false, detail: `${kind} NOT published: gh release create ${tag} failed (${(r.stderr || '').split('\n')[0] || r.status})` };
1769
+ const r = tracker.forRepo(repoAbs).releaseCreate(tag, { notesFile: file, final });
1770
+ if (!r.ok) return { ok: false, detail: `${kind} NOT published: gh release create ${tag} failed (${(r.stderr || '').split('\n')[0] || r.code})` };
1774
1771
  return { ok: true, detail: `published the GitHub ${kind} ${tag}` };
1775
1772
  } finally {
1776
1773
  try { fs.unlinkSync(file); } catch (_) { /* best-effort */ }
@@ -1963,10 +1960,9 @@ function cmdReleaseFinalize(argv) {
1963
1960
  const t0 = version0 ? trackings.get(version0) : null;
1964
1961
  if (newest && t0 && !t0.error && !t0.number && !opts.dry) {
1965
1962
  const body = releaseFinalize.trackingBody({ version: version0, row: policy.derived.row, final: policy.effective.final, testPeriodDays: policy.effective.testPeriodDays });
1966
- const c = spawnSync('gh', ['issue', 'create', '--title', releaseFinalize.trackingTitle(version0), '--body', body], { cwd: repoAbs, encoding: 'utf8' });
1967
- const m = c.status === 0 ? /\/issues\/([0-9]+)/.exec(c.stdout || '') : null;
1968
- if (!m) trackings.set(version0, { error: `could not open the tracking issue for ${version0} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'})` });
1969
- else { trackings.set(version0, { number: Number(m[1]), url: (c.stdout || '').trim(), createdAt: now, held: false }); trackingCreated = true; }
1963
+ const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(version0), body });
1964
+ if (!c.number) trackings.set(version0, { error: `could not open the tracking issue for ${version0} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'})` });
1965
+ else { trackings.set(version0, { number: c.number, url: c.url, createdAt: now, held: false }); trackingCreated = true; }
1970
1966
  }
1971
1967
 
1972
1968
  // #441: an operator-granted automatic final — the decision it names is resolved once per run, from
@@ -2069,8 +2065,8 @@ function cmdReleaseFinalize(argv) {
2069
2065
  if (!r.ok) warn(`could not comment on #${num}: ${String(r.stderr || '').split('\n')[0]}`);
2070
2066
  };
2071
2067
  const close = (num) => {
2072
- const r = spawnSync('gh', ['issue', 'close', String(num)], { cwd: repoAbs, encoding: 'utf8' });
2073
- if (r.status !== 0) warn(`could not close #${num}: ${String(r.stderr || '').split('\n')[0]}`);
2068
+ const r = tracker.forRepo(repoAbs).issueClose(num);
2069
+ if (!r.ok) warn(`could not close #${num}: ${String(r.stderr || '').split('\n')[0]}`);
2074
2070
  };
2075
2071
  // #426: one "Released in vX.Y.Z" comment on every issue the version carries (release-finalize.js
2076
2072
  // carriedIssues — the closing references in (previous final, sha]). Idempotent by event marker.
@@ -2470,7 +2466,7 @@ function cmdClose(argv) {
2470
2466
  if (already) {
2471
2467
  print(` #${num} is already closed — skipping the close; releasing and notifying anyway`);
2472
2468
  } else {
2473
- const r = git.run('gh', ['issue', 'close', String(num), '--reason', ghReason], { cwd: repoAbs });
2469
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: ghReason });
2474
2470
  if (!r.ok) {
2475
2471
  process.stderr.write(`✗ gh issue close #${num} failed (${(r.stderr || '').split('\n')[0] || r.code}) — claim untouched.\n`);
2476
2472
  return 1;
@@ -4463,11 +4459,10 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4463
4459
  // local offset is positive (tools/lib/ci-grant.js's wentGreenSince doc comment has the full
4464
4460
  // failure).
4465
4461
  let wentGreen = false;
4466
- const runsR = git.run('gh', ['run', 'list', '--branch', trunk, '-L', '100',
4467
- '--json', 'conclusion,status,createdAt'], { cwd: repoAbs });
4468
- if (runsR.ok) {
4462
+ const runsR = tracker.forRepo(repoAbs).runList({ branch: trunk, limit: 100, fields: ['conclusion', 'status', 'createdAt'] });
4463
+ if (runsR.data) {
4469
4464
  try {
4470
- wentGreen = ciGrant.wentGreenSince(JSON.parse(runsR.stdout), priorGrantMerge.at);
4465
+ wentGreen = ciGrant.wentGreenSince(runsR.data, priorGrantMerge.at);
4471
4466
  } catch (_) { /* unparseable — treat conservatively as "cannot prove it went green" */ }
4472
4467
  }
4473
4468
  redContinuousSincePriorGrant = !wentGreen;
@@ -6967,9 +6962,10 @@ function measureHeadCandidate(repoAbs, { candidatesAuto, mainRef, lastRelease, o
6967
6962
  const tagsAtSha = tagsR.ok ? tagsR.stdout.split('\n').map((t) => t.trim()).filter(Boolean) : [];
6968
6963
  let runs = null;
6969
6964
  if (isGhUsable(repoAbs)) {
6970
- const r = spawnSync('gh', ['run', 'list', '--branch', 'main', '--commit', sha, '-L', '50', '--json', 'status,conclusion,event,createdAt,updatedAt,workflowName'],
6971
- { cwd: repoAbs, encoding: 'utf8' });
6972
- if (r.status === 0) { try { const j = JSON.parse(r.stdout); runs = Array.isArray(j) ? j : null; } catch (_) { runs = null; } }
6965
+ const r = tracker.forRepo(repoAbs).runList({
6966
+ branch: 'main', commit: sha, limit: 50, fields: ['status', 'conclusion', 'event', 'createdAt', 'updatedAt', 'workflowName'],
6967
+ });
6968
+ runs = Array.isArray(r.data) ? r.data : null;
6973
6969
  }
6974
6970
  const promotion = dualTrunk ? measurePromotion(repoAbs, { sha, trunk, remote, fetched: fetchTrunk }) : null;
6975
6971
  return releaseCut.headCandidateVerdict({
@@ -11500,7 +11496,7 @@ function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
11500
11496
  const cm = git.ghIssueComment(repoAbs, pnum, body);
11501
11497
  if (!cm.ok) warnDeferred(`could not post the container-close comment on #${pnum} — left OPEN`);
11502
11498
  if (!cm.ok) break;
11503
- const r = git.run('gh', ['issue', 'close', String(pnum), '--reason', 'completed'], { cwd: repoAbs });
11499
+ const r = tracker.forRepo(repoAbs).issueClose(pnum, { reason: 'completed' });
11504
11500
  if (!r.ok) { warnDeferred(`could not close container #${pnum}: ${(r.stderr || '').split('\n')[0]}`); break; }
11505
11501
  print(` closed container #${pnum} — all ${c.total} sub-issue(s) closed (#371)`);
11506
11502
  for (const d of containerClose.containerDeliveryLabels(parent.labels)) warn(`container #${pnum} carried ${d} — a container has no deliverable of its own (#371)`);
@@ -11606,7 +11602,7 @@ function shipEvidenceClose({ repoAbs, st, sess, target, trunk, gh, closeIssues,
11606
11602
  `write. The zero-diff fact was measured from git: ${mode.why}.${shipSess}`;
11607
11603
  const c = git.ghIssueComment(repoAbs, num, body);
11608
11604
  if (!c.ok) warn(`could not post the evidence-close comment on #${num} — closing anyway`);
11609
- const r = git.run('gh', ['issue', 'close', String(num), '--reason', 'completed'], { cwd: repoAbs });
11605
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: 'completed' });
11610
11606
  if (!r.ok) { skipped.push({ num, why: `gh issue close failed: ${(r.stderr || '').split('\n')[0]}` }); continue; }
11611
11607
  closed.push(num);
11612
11608
  print(` #${num} closed with evidence.`);
@@ -14212,11 +14208,12 @@ function cmdDeliver(argv) {
14212
14208
  if (!tip || !ownerTip) return fail(`${remote}/${trunk} or ${remote}/${owner.branch} does not resolve after the fetch`);
14213
14209
 
14214
14210
  // 2. every delivery PR, any state
14215
- const r = git.run('gh', ['pr', 'list', '--base', owner.branch, '--head', trunk, '--state', 'all', '--limit', '50',
14216
- '--json', 'number,url,state,mergedAt,headRefOid,title'], { cwd: repoAbs });
14211
+ const r = tracker.forRepo(repoAbs).prList({
14212
+ base: owner.branch, head: trunk, state: 'all', limit: 50, fields: ['number', 'url', 'state', 'mergedAt', 'headRefOid', 'title'],
14213
+ });
14217
14214
  if (!r.ok) return fail(`could not list pull requests: ${(r.stderr || '').split('\n')[0]}`);
14218
- let list;
14219
- try { list = JSON.parse(r.stdout || '[]'); } catch (_) { return fail('gh pr list returned unparseable JSON'); }
14215
+ const list = r.stdout ? r.data : []; // an empty reply is no PRs here, as it always was
14216
+ if (list === null) return fail('gh pr list returned unparseable JSON');
14220
14217
  const prs = ownerBranch.classifyPrs(list);
14221
14218
 
14222
14219
  // 3. the undelivered range: since the last merged delivery's head when that head is still on
@@ -14268,7 +14265,7 @@ function cmdDeliver(argv) {
14268
14265
  return 1;
14269
14266
  }
14270
14267
  if (d.action === 'refresh') {
14271
- const e = git.run('gh', ['pr', 'edit', String(prs.open.number), '--title', text.title, '--body', text.body], { cwd: repoAbs });
14268
+ const e = tracker.forRepo(repoAbs).prEdit(prs.open.number, { title: text.title, body: text.body });
14272
14269
  if (!e.ok) return fail(`could not refresh PR #${prs.open.number}: ${(e.stderr || '').split('\n')[0]}`);
14273
14270
  out.done = `refreshed PR #${prs.open.number} (${prs.open.url || ''}) — waiting on the owner`;
14274
14271
  } else {
@@ -68,32 +68,28 @@
68
68
  * `COLAB_HUMAN=1`, the same bar `cmdPromote` and `cmdMigrationGrant` already hold.
69
69
  */
70
70
 
71
- /** The two comment markers. STABLE WIRE FORMAT — do not reword casually; `tools/colab` and any
72
- * vendored reader parse these verbatim. Deliberately a DIFFERENT leading emoji from BOTH
73
- * migration-grant's marks (🛢/🚫) AND each other, so no regex here or in migration-grant.js can
74
- * ever cross-match — a four-way collision test in ci-grant.test.js pins this. */
75
- const GRANT_MARK = '🚨 Red-trunk CI grant';
76
- const REVOKE_MARK = '🧯 Red-trunk CI grant revoked';
71
+ // The wire format — both marks (a leading emoji distinct from migration-grant's 🛢/🚫 AND from
72
+ // each other; ci-grant.test.js's four-way collision test pins it), both regexes, and the
73
+ // encode/decode pairs — lives in codec/grants.js (#498, epic #496). Re-exported below under the
74
+ // names this module always had.
75
+ const codec = require('./codec/grants');
76
+ const GRANT_MARK = codec.CI_GRANT_MARK;
77
+ const REVOKE_MARK = codec.CI_REVOKE_MARK;
78
+ const GRANT_RE = codec.CI_GRANT_RE;
79
+ const REVOKE_RE = codec.CI_REVOKE_RE;
77
80
 
78
- const GRANT_RE = /^🚨 Red-trunk CI grant — branch `([^`]*)` · red `([^`]*)`@`([^`]*)` · evidence `([^`]*)` · host `([^`]*)` · (\S+)/;
79
- const REVOKE_RE = /^🧯 Red-trunk CI grant revoked — branch `([^`]*)` · host `([^`]*)` · (\S+)/;
80
-
81
- /** The exact grant-comment body. Keep in lockstep with GRANT_RE. Carries strictly more than
81
+ /** The exact grant-comment body (codec `encodeCiGrant`, canonical tail). Carries strictly more than
82
82
  * migration-grant's equivalent: the TRUNK NAME + RED SHA it was reviewed against, and the
83
83
  * EVIDENCE RUN sha that proved the branch's own head green — both are read back and re-checked
84
84
  * by evaluateIssue, not merely stored for audit. */
85
85
  function grantCommentBody(branch, trunk, redSha, evidenceSha, host, iso) {
86
- return `${GRANT_MARK} — branch \`${branch}\` · red \`${trunk}\`@\`${redSha}\` · evidence \`${evidenceSha}\` · host \`${host}\` · ${iso}`
87
- + ` — this exempts THIS BRANCH from the trunk-CI-green precondition ONLY, only while \`${trunk}\``
88
- + ` is still at \`${redSha}\`, and expires when this issue closes.`;
86
+ return codec.encodeCiGrant({ branch, trunk, redSha, evidenceSha, host, at: iso });
89
87
  }
90
88
 
91
- /** The exact revoke-comment body. Keep in lockstep with REVOKE_RE. `branch` is the branch named in
92
- * the record for the audit trail — revocation itself is NOT branch-scoped (see evaluateIssue doc
93
- * in migration-grant.js; identical reasoning applies here). */
89
+ /** The exact revoke-comment body (codec `encodeCiRevoke`). `branch` is for the audit trail —
90
+ * revocation itself is NOT branch-scoped (see evaluateIssue doc in migration-grant.js). */
94
91
  function revokeCommentBody(branch, host, iso) {
95
- return `${REVOKE_MARK} — branch \`${branch}\` · host \`${host}\` · ${iso}`
96
- + ' — every grant on this issue up to this point is cancelled.';
92
+ return codec.encodeCiRevoke({ branch, host, at: iso });
97
93
  }
98
94
 
99
95
  /**
@@ -0,0 +1,29 @@
1
+ // Types for tools/lib/codec/decision.js (#498) — see index.d.ts.
2
+
3
+ export const DECISION_MARK: '⚖ Decision recorded';
4
+ export const REOPEN_MARK: '↩ Decision reopened';
5
+ export const DECISION_RE: RegExp;
6
+ export const REOPEN_RE: RegExp;
7
+
8
+ export interface DecodedDecision {
9
+ /** The human whose call it is — never the typist. */
10
+ ruledBy: string;
11
+ /** The options block this answers, or `-`. */
12
+ answers: string;
13
+ host: string; at: string;
14
+ /** Rest of the marker line; null = canonical (nothing). */
15
+ tail: string | null;
16
+ /** The ruling prose after one blank line, or null. */
17
+ body: string | null;
18
+ }
19
+ export function encodeDecision(d?: Partial<DecodedDecision>): string;
20
+ export function decodeDecision(text: string | null | undefined): DecodedDecision | null;
21
+
22
+ export interface DecodedReopen { ruledBy: string; host: string; at: string; tail: string | null; body: string | null; }
23
+ export function encodeReopen(r?: Partial<DecodedReopen>): string;
24
+ export function decodeReopen(text: string | null | undefined): DecodedReopen | null;
25
+
26
+ export const OPTIONS_RE: RegExp;
27
+ export const MOCKUP_RE: RegExp;
28
+ export function encodeMockup(url: string): string;
29
+ export function mockupUrls(body: unknown): string[];
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+ /**
3
+ * CODEC (#498, epic #496): the DECISION wire formats as encode/decode pairs — the `⚖ Decision
4
+ * recorded` record and its `↩ Decision reopened` counterpart, plus the two question-side markers a
5
+ * reader looks for on a `needs-decision` issue (the `<!-- decision:options` block and the `Mockup:`
6
+ * body line). Pure and synchronous: no I/O, no clock, no requires.
7
+ *
8
+ * Which decisions are live, whose are trusted, and whether a label pair is an open question or an
9
+ * interrupted write stay in tools/lib/decision-record.js, which re-exports these under its old names.
10
+ *
11
+ * STABLE WIRE FORMAT. The two marks lead with DIFFERENT glyphs, so a reopen can never parse as a
12
+ * fresh decision. Round trip: a decoded record carries `tail` (rest of the marker line; null = the
13
+ * canonical text) and `body` (the prose after one blank line; null = none), so any comment the
14
+ * regex matches re-encodes byte for byte.
15
+ */
16
+
17
+ const DECISION_MARK = '⚖ Decision recorded';
18
+ const REOPEN_MARK = '↩ Decision reopened';
19
+ const DECISION_RE = /^⚖ Decision recorded — ruled-by `([^`]*)` · answers `([^`]*)` · host `([^`]*)` · (\S+)/;
20
+ const REOPEN_RE = /^↩ Decision reopened — ruled-by `([^`]*)` · host `([^`]*)` · (\S+)/;
21
+ const DECISION_TAIL = '';
22
+ const REOPEN_TAIL = ' — every decision on this issue up to this point is superseded.';
23
+
24
+ /** The question-side options block (CONVENTIONS.md §5, *Decision options*, #126) — presence only. */
25
+ const OPTIONS_RE = /<!--\s*decision:options\b/;
26
+ /** The design-approval ask (#379): `Mockup: <url>` at the START of a body line, nothing after it. */
27
+ const MOCKUP_RE = /^Mockup:[ \t]*(\S+)[ \t]*$/gm;
28
+
29
+ // Split what follows the timestamp into the marker line's tail and the body after a blank line.
30
+ // Anything that is not "<line>\n\n<body>" stays whole in the tail, so nothing is ever dropped.
31
+ function splitRest(rest, canonical) {
32
+ const m = /^([^\n]*)\n\n([\s\S]*)$/.exec(rest);
33
+ const tail = m ? m[1] : rest;
34
+ return { tail: tail === canonical ? null : tail, body: m ? m[2] : null };
35
+ }
36
+ function joinRest(tail, body, canonical) {
37
+ return (tail == null ? canonical : tail) + (body != null && body !== '' ? `\n\n${body}` : '');
38
+ }
39
+
40
+ /**
41
+ * `{ruledBy, answers, host, at, tail?, body?}` → the decision comment. `ruledBy` names the human
42
+ * whose call it is, never the typist; `answers` is the options block this resolves, or `-`.
43
+ */
44
+ function encodeDecision({ ruledBy, answers, host, at, tail, body } = {}) {
45
+ return `${DECISION_MARK} — ruled-by \`${ruledBy}\` · answers \`${answers || '-'}\` · host \`${host}\` · ${at}`
46
+ + joinRest(tail, body, DECISION_TAIL);
47
+ }
48
+ /** A decision comment → `{ruledBy, answers, host, at, tail, body}`, or null. */
49
+ function decodeDecision(text) {
50
+ const s = String(text == null ? '' : text).trim();
51
+ const m = s.match(DECISION_RE);
52
+ if (!m) return null;
53
+ return { ruledBy: m[1], answers: m[2], host: m[3], at: m[4], ...splitRest(s.slice(m[0].length), DECISION_TAIL) };
54
+ }
55
+
56
+ /** `{ruledBy, host, at, tail?, body?}` → the reopen comment; `body` is the reason, if any. */
57
+ function encodeReopen({ ruledBy, host, at, tail, body } = {}) {
58
+ return `${REOPEN_MARK} — ruled-by \`${ruledBy}\` · host \`${host}\` · ${at}` + joinRest(tail, body, REOPEN_TAIL);
59
+ }
60
+ function decodeReopen(text) {
61
+ const s = String(text == null ? '' : text).trim();
62
+ const m = s.match(REOPEN_RE);
63
+ if (!m) return null;
64
+ return { ruledBy: m[1], host: m[2], at: m[3], ...splitRest(s.slice(m[0].length), REOPEN_TAIL) };
65
+ }
66
+
67
+ /** `url` → the `Mockup:` body line. */
68
+ function encodeMockup(url) { return `Mockup: ${url}`; }
69
+ /** Every `Mockup:` URL declared in an issue body, in order. Empty when none (or no body). */
70
+ function mockupUrls(body) {
71
+ if (typeof body !== 'string' || body === '') return [];
72
+ const out = [];
73
+ for (const m of body.replace(/\r\n/g, '\n').matchAll(MOCKUP_RE)) out.push(m[1]);
74
+ return out;
75
+ }
76
+
77
+ module.exports = {
78
+ DECISION_MARK, REOPEN_MARK, DECISION_RE, REOPEN_RE,
79
+ encodeDecision, decodeDecision, encodeReopen, decodeReopen,
80
+ OPTIONS_RE, MOCKUP_RE, encodeMockup, mockupUrls,
81
+ };
@@ -0,0 +1,54 @@
1
+ // Types for tools/lib/codec/grants.js (#498) — see index.d.ts.
2
+ // `tail` on every decoded grant: null = the canonical sentence this toolkit writes; any other string
3
+ // is kept literally so a hand-edited comment re-encodes byte for byte.
4
+
5
+ // ── human migration grant / revoke ───────────────────────────────────────────────────────────
6
+
7
+ export const MIGRATION_GRANT_MARK: '🛢 Migration grant';
8
+ export const MIGRATION_REVOKE_MARK: '🚫 Migration grant revoked';
9
+ export const MIGRATION_GRANT_RE: RegExp;
10
+ export const MIGRATION_REVOKE_RE: RegExp;
11
+
12
+ export interface DecodedMigrationGrant { branch: string; host: string; at: string; tail: string | null; }
13
+ export function encodeMigrationGrant(g?: { branch: string; host: string; at: string; tail?: string | null }): string;
14
+ export function decodeMigrationGrant(body: string | null | undefined): DecodedMigrationGrant | null;
15
+ export function encodeMigrationRevoke(r?: { branch: string; host: string; at: string; tail?: string | null }): string;
16
+ export function decodeMigrationRevoke(body: string | null | undefined): DecodedMigrationGrant | null;
17
+
18
+ // ── reviewer migration grant ─────────────────────────────────────────────────────────────────
19
+
20
+ export const REVIEW_GRANT_MARK: '🔎 Migration review grant';
21
+ export const REVIEW_GRANT_RE: RegExp;
22
+ export const REVIEWER_ROLE: 'migration-reviewer';
23
+ export const REVIEW_RECORD_FENCE: 'migration-review';
24
+ export const REVIEW_RECORD_VERSION: '1';
25
+ export interface ReviewRecordField { key: string; required: boolean; values?: string[]; re?: RegExp; hint?: string; }
26
+ export const REVIEW_RECORD_FIELDS: ReadonlyArray<ReviewRecordField>;
27
+
28
+ export interface DecodedReviewGrant {
29
+ role: string; reviewer: string; branch: string;
30
+ /** Full 40-hex sha the review covers, as written (validity is the caller's check). */
31
+ head: string;
32
+ host: string; at: string; tail: string | null;
33
+ /** The fenced record's `key: value` lines, or null when the comment has no record block. */
34
+ record: Record<string, string> | null;
35
+ /** SYNTAX findings only — never whether the review passes. */
36
+ problems: string[];
37
+ }
38
+ export function encodeReviewGrant(g?: Partial<Omit<DecodedReviewGrant, 'problems' | 'record'>> & { record?: Record<string, unknown> }): string;
39
+ export function decodeReviewGrant(body: string | null | undefined): DecodedReviewGrant | null;
40
+
41
+ // ── red-trunk CI grant / revoke ───────────────────────────────────────────────────────────────
42
+
43
+ export const CI_GRANT_MARK: '🚨 Red-trunk CI grant';
44
+ export const CI_REVOKE_MARK: '🧯 Red-trunk CI grant revoked';
45
+ export const CI_GRANT_RE: RegExp;
46
+ export const CI_REVOKE_RE: RegExp;
47
+
48
+ export interface DecodedCiGrant {
49
+ branch: string; trunk: string; redSha: string; evidenceSha: string; host: string; at: string; tail: string | null;
50
+ }
51
+ export function encodeCiGrant(g?: Omit<DecodedCiGrant, 'tail'> & { tail?: string | null }): string;
52
+ export function decodeCiGrant(body: string | null | undefined): DecodedCiGrant | null;
53
+ export function encodeCiRevoke(r?: { branch: string; host: string; at: string; tail?: string | null }): string;
54
+ export function decodeCiRevoke(body: string | null | undefined): DecodedMigrationGrant | null;
@@ -0,0 +1,184 @@
1
+ 'use strict';
2
+ /**
3
+ * CODEC (#498, epic #496): the GRANT comment wire formats as encode/decode pairs — the human
4
+ * migration grant and its revoke, the reviewer migration grant with its fenced record, and the
5
+ * red-trunk CI grant and its revoke. Pure and synchronous: no I/O, no clock, no requires.
6
+ *
7
+ * What stays OUT of here is everything that JUDGES a grant: which grants are live, whose comment is
8
+ * trusted, whether a record passes review, whether a grant still binds a HEAD. That lives in
9
+ * tools/lib/migration-grant.js and tools/lib/ci-grant.js, which re-export the names below under the
10
+ * names they always had.
11
+ *
12
+ * STABLE WIRE FORMAT. `tools/colab` and any vendored reader parse these verbatim, and an older CLI on
13
+ * another machine reads what this one writes. Every mark has a DIFFERENT leading emoji from every
14
+ * other (🛢 🚫 🔎 🚨 🧯), so no regex here can match another mark's body — a revoke that merely
15
+ * suffixed its grant would parse as a fresh grant and reopen the door it was posted to close.
16
+ *
17
+ * Round-trip rule shared by every pair below: a decoded comment carries `tail`, the text after the
18
+ * timestamp on the marker line. `tail: null` means "exactly the sentence this toolkit writes", so a
19
+ * canonical comment decodes compactly; any other tail is kept literally, so a hand-edited comment
20
+ * still re-encodes byte for byte.
21
+ */
22
+
23
+ // ── human migration grant / revoke ───────────────────────────────────────────────────────────
24
+
25
+ const MIGRATION_GRANT_MARK = '🛢 Migration grant';
26
+ const MIGRATION_REVOKE_MARK = '🚫 Migration grant revoked';
27
+ const MIGRATION_GRANT_RE = /^🛢 Migration grant — branch `([^`]*)` · host `([^`]*)` · (\S+)/;
28
+ const MIGRATION_REVOKE_RE = /^🚫 Migration grant revoked — branch `([^`]*)` · host `([^`]*)` · (\S+)/;
29
+ const MIGRATION_GRANT_TAIL = ' — this exempts THIS BRANCH only, and expires when this issue closes.';
30
+ const REVOKE_TAIL = ' — every grant on this issue up to this point is cancelled.';
31
+
32
+ function str(body) { return String(body == null ? '' : body).trim(); }
33
+ function tailOf(s, m, canonical) { const t = s.slice(m[0].length); return t === canonical ? null : t; }
34
+ function withTail(head, tail, canonical) { return head + (tail == null ? canonical : tail); }
35
+
36
+ /** `{branch, host, at, tail?}` → the grant comment. `host` is the raw name or its `h:` token. */
37
+ function encodeMigrationGrant({ branch, host, at, tail } = {}) {
38
+ return withTail(`${MIGRATION_GRANT_MARK} — branch \`${branch}\` · host \`${host}\` · ${at}`, tail, MIGRATION_GRANT_TAIL);
39
+ }
40
+ /** A grant comment → `{branch, host, at, tail}`, or null when the body is not one. */
41
+ function decodeMigrationGrant(body) {
42
+ const s = str(body);
43
+ const m = s.match(MIGRATION_GRANT_RE);
44
+ return m ? { branch: m[1], host: m[2], at: m[3], tail: tailOf(s, m, MIGRATION_GRANT_TAIL) } : null;
45
+ }
46
+ /** `{branch, host, at, tail?}` → the revoke comment. The branch is for the audit trail only. */
47
+ function encodeMigrationRevoke({ branch, host, at, tail } = {}) {
48
+ return withTail(`${MIGRATION_REVOKE_MARK} — branch \`${branch}\` · host \`${host}\` · ${at}`, tail, REVOKE_TAIL);
49
+ }
50
+ function decodeMigrationRevoke(body) {
51
+ const s = str(body);
52
+ const m = s.match(MIGRATION_REVOKE_RE);
53
+ return m ? { branch: m[1], host: m[2], at: m[3], tail: tailOf(s, m, REVOKE_TAIL) } : null;
54
+ }
55
+
56
+ // ── reviewer migration grant (#457 era): a marker line plus a fenced `migration-review` record ──
57
+
58
+ const REVIEW_GRANT_MARK = '🔎 Migration review grant';
59
+ const REVIEWER_ROLE = 'migration-reviewer';
60
+ const REVIEW_GRANT_RE = /^🔎 Migration review grant — role `([^`]*)` · reviewer `([^`]*)` · branch `([^`]*)` · head `([^`]*)` · host `([^`]*)` · (\S+)/;
61
+ const REVIEW_GRANT_TAIL = ' — bound to this HEAD: any new commit voids it; expires when this issue closes.';
62
+ /** The fenced block's info string — the record is found by it, never by position. */
63
+ const REVIEW_RECORD_FENCE = 'migration-review';
64
+ const REVIEW_RECORD_VERSION = '1';
65
+
66
+ const SHA40_RE = /^[0-9a-f]{40}$/;
67
+ const REVIEWER_ID_RE = /^[A-Za-z0-9._@-]+$/;
68
+ const CONDITION_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
69
+
70
+ /** Every key a v1 record may carry, and what each accepts. `required: false` keys may be absent.
71
+ * Order here is the order `encodeReviewGrant` writes them in — part of the wire format. */
72
+ const REVIEW_RECORD_FIELDS = Object.freeze([
73
+ { key: 'v', required: true, values: [REVIEW_RECORD_VERSION] },
74
+ { key: 'role', required: true, values: [REVIEWER_ROLE] },
75
+ { key: 'reviewer', required: true, re: REVIEWER_ID_RE, hint: 'letters, digits, . _ @ -' },
76
+ { key: 'head', required: true, re: SHA40_RE, hint: 'a full 40-hex commit sha' },
77
+ { key: 'verdict', required: true, values: ['approve', 'reject'] },
78
+ { key: 'checklist', required: true, values: ['pass', 'fail'] },
79
+ { key: 'checklist-items', required: false, re: /^\d+\/\d+$/, hint: 'N/M, e.g. 7/7' },
80
+ { key: 'escalation', required: true, re: CONDITION_ID_RE, hint: 'a condition id, lowercase-hyphenated' },
81
+ { key: 'escalation-result', required: true, values: ['clear', 'escalated'] },
82
+ { key: 'ci-roundtrip', required: true, values: ['pass', 'fail', 'pending'] },
83
+ { key: 'ci-run', required: false, re: /^\S+$/, hint: 'a run id or URL, no spaces' },
84
+ ]);
85
+
86
+ /**
87
+ * `{role, reviewer, branch, head, host, at, tail?, record}` → marker line, blank line, fenced
88
+ * record. Record keys are written in REVIEW_RECORD_FIELDS order, then any other key in the object's
89
+ * own order; an empty/absent value is omitted. Validating the record is the caller's job
90
+ * (migration-grant.js `validateReviewRecord`) — the codec writes what it is given.
91
+ */
92
+ function encodeReviewGrant({ role, reviewer, branch, head, host, at, tail, record } = {}) {
93
+ const marker = withTail(`${REVIEW_GRANT_MARK} — role \`${role}\` · reviewer \`${reviewer}\` · branch \`${branch}\``
94
+ + ` · head \`${head}\` · host \`${host}\` · ${at}`, tail, REVIEW_GRANT_TAIL);
95
+ const rec = record || {};
96
+ const known = REVIEW_RECORD_FIELDS.map((f) => f.key);
97
+ const keys = [...known.filter((k) => Object.prototype.hasOwnProperty.call(rec, k)),
98
+ ...Object.keys(rec).filter((k) => !known.includes(k))];
99
+ const lines = [];
100
+ for (const k of keys) {
101
+ const v = rec[k];
102
+ if (v === undefined || v === null || String(v) === '') continue;
103
+ lines.push(`${k}: ${v}`);
104
+ }
105
+ return `${marker}\n\n\`\`\`${REVIEW_RECORD_FENCE}\n${lines.join('\n')}\n\`\`\``;
106
+ }
107
+
108
+ /**
109
+ * A reviewer-grant comment → `{role, reviewer, branch, head, host, at, tail, record, problems}`, or
110
+ * null when the first line is not a reviewer-grant marker. The record is the FIRST fenced block whose
111
+ * info string is exactly `migration-review`; text outside it is ignored. `problems` holds SYNTAX
112
+ * findings only (no block, a line that is not `key: value`, a duplicate key) — whether the record's
113
+ * values are acceptable is migration-grant.js's `validateReviewRecord`, never the codec's.
114
+ */
115
+ function decodeReviewGrant(body) {
116
+ const text = String(body == null ? '' : body).replace(/\r\n/g, '\n').trim();
117
+ const m = text.match(REVIEW_GRANT_RE);
118
+ if (!m) return null;
119
+ const nl = text.indexOf('\n');
120
+ const line = nl === -1 ? text : text.slice(0, nl);
121
+ const t = line.slice(m[0].length);
122
+ const out = { role: m[1], reviewer: m[2], branch: m[3], head: m[4], host: m[5], at: m[6],
123
+ tail: t === REVIEW_GRANT_TAIL ? null : t, record: null, problems: [] };
124
+ const fence = new RegExp('^```' + REVIEW_RECORD_FENCE + '[ \\t]*\\n([\\s\\S]*?)^```[ \\t]*$', 'm');
125
+ const fm = text.match(fence);
126
+ if (!fm) {
127
+ out.problems.push(`no \`\`\`${REVIEW_RECORD_FENCE} block — a reviewer grant without its review record is not a grant`);
128
+ return out;
129
+ }
130
+ const record = {};
131
+ for (const raw of fm[1].split('\n')) {
132
+ const l = raw.trim();
133
+ if (l === '') continue;
134
+ const kv = l.match(/^([a-z][a-z-]*):\s*(.*)$/);
135
+ if (!kv) { out.problems.push(`record line ${JSON.stringify(l)} is not "key: value"`); continue; }
136
+ if (Object.prototype.hasOwnProperty.call(record, kv[1])) { out.problems.push(`"${kv[1]}" appears twice`); continue; }
137
+ record[kv[1]] = kv[2].trim();
138
+ }
139
+ out.record = record;
140
+ return out;
141
+ }
142
+
143
+ // ── red-trunk CI grant / revoke ───────────────────────────────────────────────────────────────
144
+
145
+ const CI_GRANT_MARK = '🚨 Red-trunk CI grant';
146
+ const CI_REVOKE_MARK = '🧯 Red-trunk CI grant revoked';
147
+ const CI_GRANT_RE = /^🚨 Red-trunk CI grant — branch `([^`]*)` · red `([^`]*)`@`([^`]*)` · evidence `([^`]*)` · host `([^`]*)` · (\S+)/;
148
+ const CI_REVOKE_RE = /^🧯 Red-trunk CI grant revoked — branch `([^`]*)` · host `([^`]*)` · (\S+)/;
149
+
150
+ /** The CI grant's canonical tail names the trunk and the red sha it was reviewed against. */
151
+ function ciGrantTail(trunk, redSha) {
152
+ return ` — this exempts THIS BRANCH from the trunk-CI-green precondition ONLY, only while \`${trunk}\``
153
+ + ` is still at \`${redSha}\`, and expires when this issue closes.`;
154
+ }
155
+
156
+ /** `{branch, trunk, redSha, evidenceSha, host, at, tail?}` → the CI grant comment. */
157
+ function encodeCiGrant({ branch, trunk, redSha, evidenceSha, host, at, tail } = {}) {
158
+ return withTail(`${CI_GRANT_MARK} — branch \`${branch}\` · red \`${trunk}\`@\`${redSha}\` · evidence \`${evidenceSha}\``
159
+ + ` · host \`${host}\` · ${at}`, tail, ciGrantTail(trunk, redSha));
160
+ }
161
+ function decodeCiGrant(body) {
162
+ const s = str(body);
163
+ const m = s.match(CI_GRANT_RE);
164
+ if (!m) return null;
165
+ return { branch: m[1], trunk: m[2], redSha: m[3], evidenceSha: m[4], host: m[5], at: m[6],
166
+ tail: tailOf(s, m, ciGrantTail(m[2], m[3])) };
167
+ }
168
+ function encodeCiRevoke({ branch, host, at, tail } = {}) {
169
+ return withTail(`${CI_REVOKE_MARK} — branch \`${branch}\` · host \`${host}\` · ${at}`, tail, REVOKE_TAIL);
170
+ }
171
+ function decodeCiRevoke(body) {
172
+ const s = str(body);
173
+ const m = s.match(CI_REVOKE_RE);
174
+ return m ? { branch: m[1], host: m[2], at: m[3], tail: tailOf(s, m, REVOKE_TAIL) } : null;
175
+ }
176
+
177
+ module.exports = {
178
+ MIGRATION_GRANT_MARK, MIGRATION_REVOKE_MARK, MIGRATION_GRANT_RE, MIGRATION_REVOKE_RE,
179
+ encodeMigrationGrant, decodeMigrationGrant, encodeMigrationRevoke, decodeMigrationRevoke,
180
+ REVIEW_GRANT_MARK, REVIEW_GRANT_RE, REVIEWER_ROLE, REVIEW_RECORD_FENCE, REVIEW_RECORD_VERSION, REVIEW_RECORD_FIELDS,
181
+ encodeReviewGrant, decodeReviewGrant,
182
+ CI_GRANT_MARK, CI_REVOKE_MARK, CI_GRANT_RE, CI_REVOKE_RE,
183
+ encodeCiGrant, decodeCiGrant, encodeCiRevoke, decodeCiRevoke,
184
+ };
@@ -0,0 +1,26 @@
1
+ // Types for tools/lib/codec/hold.js (#498) — see index.d.ts.
2
+
3
+ export type WakeKind = 'review-by' | 'edge' | 'ruling' | 'issueClosed' | 'branchLanded' | 'trunkAt' | 'labelPresent' | 'after';
4
+ export const WAKE_KINDS: ReadonlyArray<WakeKind>;
5
+ export const CHECKABLE_KINDS: ReadonlyArray<WakeKind>;
6
+ export const WAKE_KINDS_TEXT: string;
7
+
8
+ export interface WakeCondition { kind: WakeKind; arg: string | null; raw: string; }
9
+ export function parseWake(raw: unknown): WakeCondition | null;
10
+ export function parseWakeLine(value: string | string[] | unknown):
11
+ | { ok: true; conditions: WakeCondition[] }
12
+ | { ok: false; error: string };
13
+ export function parseQualifiedIssueRef(arg: unknown): { slug: string; number: number } | null;
14
+
15
+ export const HOLD_RE: RegExp;
16
+ export const BECAUSE_RE: RegExp;
17
+ export interface DecodedHold {
18
+ label: string;
19
+ owner: string;
20
+ /** The `wake:` field as written — `parseWakeLine` decides whether it names a wake. */
21
+ wake: string;
22
+ /** The `Because:` line's text, or null when the comment is the `Hold:` line alone. */
23
+ because: string | null;
24
+ }
25
+ export function encodeHold(h?: { label: string; owner: string; wake: string | string[]; because?: string | null }): string;
26
+ export function decodeHold(body: string | null | undefined): DecodedHold | null;