@futurelastic/colab-handbook 1.12.0-rc.57 → 1.12.0-rc.59

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
@@ -17,6 +17,10 @@
17
17
  "tools/colab",
18
18
  "tools/lib/*.js",
19
19
  "!tools/lib/*.test.js",
20
+ "tools/lib/codec/*.js",
21
+ "tools/lib/codec/*.d.ts",
22
+ "tools/lib/codec/samples.json",
23
+ "!tools/lib/codec/*.test.js",
20
24
  "templates/",
21
25
  "audit/audit.mjs"
22
26
  ],
@@ -27,5 +31,5 @@
27
31
  "engines": {
28
32
  "node": ">=18"
29
33
  },
30
- "version": "1.12.0-rc.57"
34
+ "version": "1.12.0-rc.59"
31
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');
@@ -57,6 +58,7 @@ const axisAuthority = require('./lib/axis-authority');
57
58
  const writesAuthority = require('./lib/writes-authority');
58
59
  const claimIdentity = require('./lib/claim-identity');
59
60
  const claimComments = require('./lib/claim-comments');
61
+ const codec = require('./lib/codec');
60
62
  const machine = require('./lib/machine');
61
63
  const targetSync = require('./lib/ship-target-sync');
62
64
  const shipBatch = require('./lib/ship-batch');
@@ -243,9 +245,10 @@ function ghUnusableWhy(repoAbs) {
243
245
  // GitHub offers no atomic check-and-set on labels/assignees.
244
246
  // ---------------------------------------------------------------------------
245
247
 
246
- // The claim/release comment markers and parsers live in tools/lib/claim-comments.js (#369/#375) —
248
+ // The claim/release comment markers and their encode/decode pairs live in tools/lib/codec/claim.js
249
+ // (#497); the readers built on them (liveness, tie-break) in tools/lib/claim-comments.js (#369/#375) —
247
250
  // a STABLE WIRE FORMAT the refusal path, the tie-break and dashboards grep. Do not reword casually.
248
- const { CLAIM_MARK, RELEASE_MARK, liveClaimComments, tieBreakVerdict } = claimComments;
251
+ const { liveClaimComments, tieBreakVerdict } = claimComments; // the format itself: codec/claim.js (#497)
249
252
 
250
253
  /**
251
254
  * #369: may a comment colab posts to THIS repo's tracker name the host in its `host` field? The
@@ -436,14 +439,6 @@ function identityLegend(entries) {
436
439
  print(' Repair: colab worktree tag <worktree> --session <url>');
437
440
  }
438
441
 
439
- /** The ` · session …` comment suffix, or '' — keeps the no-identity comment byte-stable. */
440
- function sessionCommentSuffix(session, sessionName) {
441
- if (sessionName && session) return ` · session [${sessionName}](${session})`; // both → markdown link
442
- if (session) return ` · session ${session}`; // url only → legacy form
443
- if (sessionName) return ` · session ${sessionName}`; // name only
444
- return '';
445
- }
446
-
447
442
  /**
448
443
  * Worktree lifecycle status, backfilled-on-read: entries created before this field existed (or by
449
444
  * an older colab) render as `running`. Values: `running` (default, at create) → `merged` (branch
@@ -452,17 +447,18 @@ function sessionCommentSuffix(session, sessionName) {
452
447
  */
453
448
  function wtStatus(wt) { return (wt && wt.status) || 'running'; }
454
449
 
455
- /** The exact claim-comment body. Keep in lockstep with CLAIM_RE/parseSessionField and the README. */
450
+ /**
451
+ * The exact claim-comment body. The format itself is codec/claim.js `encodeClaim` (#497); this
452
+ * supplies what the codec deliberately does not hold — the clock and the machine digest. `-` stands
453
+ * for "no branch"/"no worktree" (#53, it used to be the word `trunk`). `host` is the raw hostname
454
+ * where the destination may name it, the `h:` token where it may not (#369, `commentHost`); the
455
+ * comparable identity is the machine digest beside it (#327), omitted when no id resolved.
456
+ */
456
457
  function claimCommentBody(wtName, branch, session, sessionName, host = HOST) {
457
- // `-` for "no branch", matching the worktree field beside it. It used to be the word `trunk`,
458
- // which read as a branch name that never existed (#53).
459
- const base = `${CLAIM_MARK} — worktree \`${wtName || '-'}\` · branch \`${branch || '-'}\` · host \`${host}\` · ${nowISO()}`;
460
- // #327: `host` is the raw hostname where the destination may name it, the `h:` token where it
461
- // may not (#369, `commentHost`); the comparable identity is the machine digest beside it.
462
- // Omitted when no id resolved.
463
- const token = machine.machineToken(myMachineId());
464
- const mach = token ? ` · machine \`${token}\`` : '';
465
- return base + mach + sessionCommentSuffix(session, sessionName);
458
+ return codec.encodeClaim({
459
+ worktree: wtName, branch, host, at: nowISO(),
460
+ machine: machine.machineToken(myMachineId()) || '', session, sessionName,
461
+ });
466
462
  }
467
463
 
468
464
  /** Issues whose EXISTING local claim sits on a different worktree than the one we're claiming onto. */
@@ -716,7 +712,7 @@ function postClaimComment(repoAbs, num, wtName, branch, session, sessionName) {
716
712
  function postReleaseComment(repoAbs, num) {
717
713
  const info = git.ghIssueView(repoAbs, num, ['state']);
718
714
  if (info && info.state === 'CLOSED') return true; // don't chatter on a closed issue
719
- const r = git.ghIssueComment(repoAbs, num, RELEASE_MARK);
715
+ const r = git.ghIssueComment(repoAbs, num, codec.encodeRelease());
720
716
  if (!r.ok) { warnDeferred(`could not post release comment on #${num} (${r.stderr.split('\n')[0] || r.code})`); return false; }
721
717
  return true;
722
718
  }
@@ -1328,16 +1324,13 @@ no-op; 1 when refused.
1328
1324
  function readAllIssuesForSwitches(repoAbs) {
1329
1325
  const LIMIT = 5000;
1330
1326
  // title/labels/createdAt/url are additive (#339): `release finalize` finds its tracking issue in the same read.
1331
- const r = spawnSync('gh', ['issue', 'list', '--state', 'all', '--limit', String(LIMIT), '--json', 'number,state,stateReason,body,title,labels,createdAt,closedAt,url'],
1332
- { cwd: repoAbs, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 });
1333
- if (r.status !== 0) return null;
1334
- try {
1335
- const list = JSON.parse(r.stdout);
1336
- // A full page may be a truncated one — an unread marker is not a cleared one.
1337
- return Array.isArray(list) && list.length < LIMIT ? list : null;
1338
- } catch (_) {
1339
- return null;
1340
- }
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;
1341
1334
  }
1342
1335
 
1343
1336
  /** [{status, path, content}] for every path changed between `from` (null = the empty tree) and `sha`; null on a git failure. */
@@ -1678,15 +1671,14 @@ function cmdReleaseCut(argv) {
1678
1671
  announced = announceCarried(repoAbs, { tagNames: [...tags, verdict.tag], exclude, version: verdict.tag, sha });
1679
1672
  if (fastFacts.tracking) {
1680
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.`);
1681
- const r = spawnSync('gh', ['issue', 'close', String(fastFacts.tracking.number)], { cwd: repoAbs, encoding: 'utf8' });
1682
- 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]}`);
1683
1676
  }
1684
1677
  } else if (handoff && verdict.version) {
1685
1678
  let num = fastFacts.tracking ? fastFacts.tracking.number : null;
1686
1679
  if (!num && issues !== null) {
1687
- const c = spawnSync('gh', ['issue', 'create', '--title', releaseFinalize.trackingTitle(verdict.version), '--body', releaseCut.handoffTrackingBody(verdict.version)], { cwd: repoAbs, encoding: 'utf8' });
1688
- const m = c.status === 0 ? /\/issues\/([0-9]+)/.exec(c.stdout || '') : null;
1689
- 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;
1690
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`);
1691
1683
  }
1692
1684
  if (num) {
@@ -1762,8 +1754,8 @@ function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false })
1762
1754
  // #446: a deploy-tag-fast final is published as a full release, marked latest.
1763
1755
  const kind = final ? 'release' : 'pre-release';
1764
1756
  if (!isGhUsable(repoAbs)) return { ok: false, detail: `${kind} NOT published: gh not usable (${ghUnusableWhy(repoAbs)})` };
1765
- const view = spawnSync('gh', ['release', 'view', tag, '--json', 'tagName'], { cwd: repoAbs, encoding: 'utf8' });
1766
- 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` };
1767
1759
  let notes;
1768
1760
  try {
1769
1761
  notes = lastFinal ? buildReleaseNotes(repoAbs, `${lastFinal}..${tag}`, lastFinal).out : `## ${tag}\n\nFirst release.\n`;
@@ -1774,8 +1766,8 @@ function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false })
1774
1766
  const file = path.join(os.tmpdir(), `colab-release-notes-${process.pid}-${tag}.md`);
1775
1767
  fs.writeFileSync(file, notes);
1776
1768
  try {
1777
- const r = spawnSync('gh', final ? releaseCut.finalReleaseArgs(tag, file) : releaseCut.prereleaseArgs(tag, file), { cwd: repoAbs, encoding: 'utf8' });
1778
- 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})` };
1779
1771
  return { ok: true, detail: `published the GitHub ${kind} ${tag}` };
1780
1772
  } finally {
1781
1773
  try { fs.unlinkSync(file); } catch (_) { /* best-effort */ }
@@ -1968,10 +1960,9 @@ function cmdReleaseFinalize(argv) {
1968
1960
  const t0 = version0 ? trackings.get(version0) : null;
1969
1961
  if (newest && t0 && !t0.error && !t0.number && !opts.dry) {
1970
1962
  const body = releaseFinalize.trackingBody({ version: version0, row: policy.derived.row, final: policy.effective.final, testPeriodDays: policy.effective.testPeriodDays });
1971
- const c = spawnSync('gh', ['issue', 'create', '--title', releaseFinalize.trackingTitle(version0), '--body', body], { cwd: repoAbs, encoding: 'utf8' });
1972
- const m = c.status === 0 ? /\/issues\/([0-9]+)/.exec(c.stdout || '') : null;
1973
- if (!m) trackings.set(version0, { error: `could not open the tracking issue for ${version0} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'})` });
1974
- 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; }
1975
1966
  }
1976
1967
 
1977
1968
  // #441: an operator-granted automatic final — the decision it names is resolved once per run, from
@@ -2074,8 +2065,8 @@ function cmdReleaseFinalize(argv) {
2074
2065
  if (!r.ok) warn(`could not comment on #${num}: ${String(r.stderr || '').split('\n')[0]}`);
2075
2066
  };
2076
2067
  const close = (num) => {
2077
- const r = spawnSync('gh', ['issue', 'close', String(num)], { cwd: repoAbs, encoding: 'utf8' });
2078
- 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]}`);
2079
2070
  };
2080
2071
  // #426: one "Released in vX.Y.Z" comment on every issue the version carries (release-finalize.js
2081
2072
  // carriedIssues — the closing references in (previous final, sha]). Idempotent by event marker.
@@ -2475,7 +2466,7 @@ function cmdClose(argv) {
2475
2466
  if (already) {
2476
2467
  print(` #${num} is already closed — skipping the close; releasing and notifying anyway`);
2477
2468
  } else {
2478
- const r = git.run('gh', ['issue', 'close', String(num), '--reason', ghReason], { cwd: repoAbs });
2469
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: ghReason });
2479
2470
  if (!r.ok) {
2480
2471
  process.stderr.write(`✗ gh issue close #${num} failed (${(r.stderr || '').split('\n')[0] || r.code}) — claim untouched.\n`);
2481
2472
  return 1;
@@ -4468,11 +4459,10 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4468
4459
  // local offset is positive (tools/lib/ci-grant.js's wentGreenSince doc comment has the full
4469
4460
  // failure).
4470
4461
  let wentGreen = false;
4471
- const runsR = git.run('gh', ['run', 'list', '--branch', trunk, '-L', '100',
4472
- '--json', 'conclusion,status,createdAt'], { cwd: repoAbs });
4473
- if (runsR.ok) {
4462
+ const runsR = tracker.forRepo(repoAbs).runList({ branch: trunk, limit: 100, fields: ['conclusion', 'status', 'createdAt'] });
4463
+ if (runsR.data) {
4474
4464
  try {
4475
- wentGreen = ciGrant.wentGreenSince(JSON.parse(runsR.stdout), priorGrantMerge.at);
4465
+ wentGreen = ciGrant.wentGreenSince(runsR.data, priorGrantMerge.at);
4476
4466
  } catch (_) { /* unparseable — treat conservatively as "cannot prove it went green" */ }
4477
4467
  }
4478
4468
  redContinuousSincePriorGrant = !wentGreen;
@@ -6972,9 +6962,10 @@ function measureHeadCandidate(repoAbs, { candidatesAuto, mainRef, lastRelease, o
6972
6962
  const tagsAtSha = tagsR.ok ? tagsR.stdout.split('\n').map((t) => t.trim()).filter(Boolean) : [];
6973
6963
  let runs = null;
6974
6964
  if (isGhUsable(repoAbs)) {
6975
- const r = spawnSync('gh', ['run', 'list', '--branch', 'main', '--commit', sha, '-L', '50', '--json', 'status,conclusion,event,createdAt,updatedAt,workflowName'],
6976
- { cwd: repoAbs, encoding: 'utf8' });
6977
- 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;
6978
6969
  }
6979
6970
  const promotion = dualTrunk ? measurePromotion(repoAbs, { sha, trunk, remote, fetched: fetchTrunk }) : null;
6980
6971
  return releaseCut.headCandidateVerdict({
@@ -11505,7 +11496,7 @@ function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
11505
11496
  const cm = git.ghIssueComment(repoAbs, pnum, body);
11506
11497
  if (!cm.ok) warnDeferred(`could not post the container-close comment on #${pnum} — left OPEN`);
11507
11498
  if (!cm.ok) break;
11508
- const r = git.run('gh', ['issue', 'close', String(pnum), '--reason', 'completed'], { cwd: repoAbs });
11499
+ const r = tracker.forRepo(repoAbs).issueClose(pnum, { reason: 'completed' });
11509
11500
  if (!r.ok) { warnDeferred(`could not close container #${pnum}: ${(r.stderr || '').split('\n')[0]}`); break; }
11510
11501
  print(` closed container #${pnum} — all ${c.total} sub-issue(s) closed (#371)`);
11511
11502
  for (const d of containerClose.containerDeliveryLabels(parent.labels)) warn(`container #${pnum} carried ${d} — a container has no deliverable of its own (#371)`);
@@ -11611,7 +11602,7 @@ function shipEvidenceClose({ repoAbs, st, sess, target, trunk, gh, closeIssues,
11611
11602
  `write. The zero-diff fact was measured from git: ${mode.why}.${shipSess}`;
11612
11603
  const c = git.ghIssueComment(repoAbs, num, body);
11613
11604
  if (!c.ok) warn(`could not post the evidence-close comment on #${num} — closing anyway`);
11614
- const r = git.run('gh', ['issue', 'close', String(num), '--reason', 'completed'], { cwd: repoAbs });
11605
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: 'completed' });
11615
11606
  if (!r.ok) { skipped.push({ num, why: `gh issue close failed: ${(r.stderr || '').split('\n')[0]}` }); continue; }
11616
11607
  closed.push(num);
11617
11608
  print(` #${num} closed with evidence.`);
@@ -14217,11 +14208,12 @@ function cmdDeliver(argv) {
14217
14208
  if (!tip || !ownerTip) return fail(`${remote}/${trunk} or ${remote}/${owner.branch} does not resolve after the fetch`);
14218
14209
 
14219
14210
  // 2. every delivery PR, any state
14220
- const r = git.run('gh', ['pr', 'list', '--base', owner.branch, '--head', trunk, '--state', 'all', '--limit', '50',
14221
- '--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
+ });
14222
14214
  if (!r.ok) return fail(`could not list pull requests: ${(r.stderr || '').split('\n')[0]}`);
14223
- let list;
14224
- 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');
14225
14217
  const prs = ownerBranch.classifyPrs(list);
14226
14218
 
14227
14219
  // 3. the undelivered range: since the last merged delivery's head when that head is still on
@@ -14273,7 +14265,7 @@ function cmdDeliver(argv) {
14273
14265
  return 1;
14274
14266
  }
14275
14267
  if (d.action === 'refresh') {
14276
- 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 });
14277
14269
  if (!e.ok) return fail(`could not refresh PR #${prs.open.number}: ${(e.stderr || '').split('\n')[0]}`);
14278
14270
  out.done = `refreshed PR #${prs.open.number} (${prs.open.url || ''}) — waiting on the owner`;
14279
14271
  } else {
@@ -14,62 +14,15 @@
14
14
  const claimIdentity = require('./claim-identity');
15
15
  const machine = require('./machine');
16
16
 
17
- const CLAIM_MARK = '🔒 Claimed';
18
- const RELEASE_MARK = '✅ Released';
17
+ // The wire format itself — markers, regexes, the session/identity fields and the claim/release
18
+ // encode/decode pairs — lives in codec/claim.js (#497). Re-exported below under the names this
19
+ // module always had, so no caller breaks.
20
+ const codec = require('./codec/claim');
21
+ const { CLAIM_MARK, RELEASE_MARK, CLAIM_RE, SESSION_RE, MACHINE_RE, YIELD_RE, parseSessionField, parseIdentity } = codec;
19
22
  // #378: how far BEFORE our own claim a rival's live claim can be and still count as "simultaneous".
20
23
  // Racers post within seconds of each other; 10 minutes is deliberately generous so a slow `gh` never
21
24
  // splits a real race, while a claim weeks old — abandoned, or released only in prose — is not a race.
22
25
  const RACE_WINDOW_MS = 10 * 60 * 1000;
23
- // Parses a claim comment body back into {worktree, branch, host, date}. The `· <host>` field is
24
- // what lets the tie-break tell two machines of the SAME GitHub user apart. On a public destination
25
- // it carries an opaque `h:` token instead of the raw name (#369, machine.js `hostToken`) — same
26
- // field, same position, so this regex and every older parser read both shapes. The optional
27
- // trailing `· session <value>` (added 2026-07) is captured separately by SESSION_RE so this regex
28
- // stays byte-stable for session-less comments.
29
- const CLAIM_RE = /🔒 Claimed — worktree `([^`]*)` · branch `([^`]*)` · host `([^`]*)` · (\S+)/;
30
- // The `· session <field>` tail, captured as the rest of the line. parseSessionField() then decodes
31
- // the THREE shapes it can take — `[name](url)`, a bare URL, or a bare name — plus the legacy
32
- // plain-URL form written before sessionName existed.
33
- const SESSION_RE = /· session (.+)$/;
34
- // #327: the claimant's machine, as the public `m:` digest (tools/lib/machine.js `machineToken`),
35
- // written AFTER the timestamp and BEFORE the session suffix — so CLAIM_RE's four groups and
36
- // SESSION_RE's end anchor both parse a new comment exactly as they parse a legacy one, and a legacy
37
- // comment (no such field) simply has no machine and is compared by host.
38
- const MACHINE_RE = /· machine `(m:[0-9a-f]{12})`/;
39
- // A yield: the loser of a race releases, naming the winner by its identity string
40
- // (`claimIdentity.identityString` — `login@host`, or `login@host#session` under the fine setting).
41
- const YIELD_RE = /^✅ Released \(yielded — earlier claim by (.+?) wins\)/;
42
-
43
- /**
44
- * Decode the `· session <field>` tail of a claim comment into { sessionName, session }. Accepts:
45
- * `[name](url)` → both; bare `https://…`/`session_…` → url only; any other bare token → name.
46
- * The bare-URL branch is exactly the LEGACY format written before sessionName existed, so old
47
- * comments keep parsing. Returns empty strings when there is no session tail.
48
- */
49
- function parseSessionField(body) {
50
- const m = String(body).match(SESSION_RE);
51
- if (!m) return { sessionName: '', session: '' };
52
- const v = m[1].trim();
53
- const link = v.match(/^\[([^\]]*)\]\((.*)\)$/);
54
- if (link) return { sessionName: link[1], session: link[2] };
55
- // #306: the shape test lives in claimIdentity.looksLikeSessionId — one copy of the rule.
56
- if (claimIdentity.looksLikeSessionId(v)) return { sessionName: '', session: v };
57
- return { sessionName: v, session: '' };
58
- }
59
-
60
- /** `login@host[#session]` → its parts. Logins cannot contain `@`, hosts cannot contain `#`. */
61
- function parseIdentity(s) {
62
- const str = String(s || '').trim();
63
- const at = str.indexOf('@');
64
- if (at <= 0) return null;
65
- const rest = str.slice(at + 1);
66
- const hash = rest.indexOf('#');
67
- return {
68
- login: str.slice(0, at),
69
- host: hash === -1 ? rest : rest.slice(0, hash),
70
- session: hash === -1 ? '' : rest.slice(hash + 1),
71
- };
72
- }
73
26
 
74
27
  /**
75
28
  * Is claim `c` the one a yield NAMED as its winner? Login exact, host by `sameHostName` (so a
@@ -91,11 +44,10 @@ function isNamedWinner(c, named) {
91
44
  function releaseComments(sorted) {
92
45
  const out = [];
93
46
  for (const c of sorted) {
94
- const body = String(c.body || '').trim();
95
- if (!body.startsWith(RELEASE_MARK)) continue;
47
+ const rel = codec.decodeRelease(c.body || '');
48
+ if (!rel) continue;
96
49
  const login = (c.author && c.author.login) || '';
97
- const y = body.match(YIELD_RE);
98
- if (y) out.push({ kind: 'yield', login, at: c.createdAt, winner: parseIdentity(y[1]) });
50
+ if (rel.kind === 'yield') out.push({ kind: 'yield', login, at: c.createdAt, winner: parseIdentity(rel.winner) });
99
51
  else out.push({ kind: 'release', login, at: c.createdAt });
100
52
  }
101
53
  return out;
@@ -133,14 +85,11 @@ function liveClaimComments(comments, comps) {
133
85
  const releases = releaseComments(sorted);
134
86
  const live = [];
135
87
  for (const c of sorted) {
136
- const body = String(c.body || '').trim();
137
- const m = body.match(CLAIM_RE);
138
- if (!m) continue;
88
+ const claim = codec.decodeClaim(c.body || ''); // [name](url) / url / name / legacy, machine or not
89
+ if (!claim) continue;
139
90
  const login = (c.author && c.author.login) || '';
140
- const host = m[3];
141
- const { session, sessionName } = parseSessionField(body); // handles [name](url) / url / name / legacy
142
- const mm = body.match(MACHINE_RE); // #327 — absent on a legacy comment: compared by host
143
- const machineTok = mm ? mm[1] : '';
91
+ const { host, session, sessionName } = claim;
92
+ const machineTok = claim.machine; // #327 — '' on a legacy comment: compared by host
144
93
  const at = c.createdAt;
145
94
  const entry = { login, host, machine: machineTok, session, sessionName, at };
146
95
  const cancelled = releases.some((r) => r.at > at && (r.kind === 'release'
@@ -203,7 +152,7 @@ function yieldReleaseBody(winner, { redact = false } = {}) {
203
152
  const tail = id.startsWith(head) ? id.slice(head.length) : '';
204
153
  id = `${winner.login}@${machine.hostToken(winner.host)}${tail}`;
205
154
  }
206
- return `${RELEASE_MARK} (yielded — earlier claim by ${id} wins)`;
155
+ return codec.encodeRelease({ winner: id });
207
156
  }
208
157
 
209
158
  module.exports = {
@@ -168,8 +168,9 @@ function mergeClaimRecord(existing, incoming, { sameHolder } = {}) {
168
168
 
169
169
  /**
170
170
  * Does `v` look like a session ID a consumer could actually JOIN on — a URL, or a `session_…`
171
- * token embedded in one (#306)? The repo's ONE answer to that question: `parseSessionField`
172
- * (tools/colab) decodes a claim comment's `· session <field>` tail with exactly this test, and
171
+ * token embedded in one (#306)? The repo's ONE answer to that question — defined in codec/claim.js
172
+ * since #497 and re-exported here: `parseSessionField` (codec/claim.js) decodes a claim comment's
173
+ * `· session <field>` tail with exactly this test, and
173
174
  * `warnWeakIdentity` warns with it. Two copies of a shape rule drift, and this one decides
174
175
  * whether a hold can ever be released by its own owner, so there is one.
175
176
  *
@@ -182,11 +183,7 @@ function mergeClaimRecord(existing, incoming, { sameHolder } = {}) {
182
183
  * False for '' / null: absence is `warnWeakIdentity`'s and `requirePlaceIdentity`'s subject
183
184
  * (#11/#242), never this predicate's — callers test blankness first.
184
185
  */
185
- function looksLikeSessionId(v) {
186
- const s = String(v == null ? '' : v).trim();
187
- if (!s) return false;
188
- return /^https?:\/\//.test(s) || /session_[\w-]+/.test(s);
189
- }
186
+ const { looksLikeSessionId } = require('./codec/claim'); // one copy of the rule, in the codec (#497)
190
187
 
191
188
  module.exports = {
192
189
  DEFAULT_COMPONENTS, FINE_COMPONENTS,
@@ -0,0 +1,41 @@
1
+ // Types for tools/lib/codec/claim.js (#497) — see index.d.ts.
2
+
3
+ // ── claim / release comments ─────────────────────────────────────────────────────────────────
4
+
5
+ export const CLAIM_MARK: '🔒 Claimed';
6
+ export const RELEASE_MARK: '✅ Released';
7
+ export const CLAIM_RE: RegExp;
8
+ export const SESSION_RE: RegExp;
9
+ export const MACHINE_RE: RegExp;
10
+ export const YIELD_RE: RegExp;
11
+
12
+ export function looksLikeSessionId(v: unknown): boolean;
13
+
14
+ export interface SessionField { session: string; sessionName: string; }
15
+ export function encodeSessionField(session?: string, sessionName?: string): string;
16
+ export function parseSessionField(body: string): SessionField;
17
+
18
+ export interface Identity { login: string; host: string; session: string; }
19
+ export function encodeIdentity(id?: { login: string; host: string; session?: string }): string;
20
+ export function parseIdentity(s: string | null | undefined): Identity | null;
21
+
22
+ export interface DecodedClaim extends SessionField {
23
+ /** `-` when the claim names no worktree — kept literally so the pair round-trips. */
24
+ worktree: string;
25
+ /** `-` when the claim names no branch (#53). */
26
+ branch: string;
27
+ /** Raw hostname, or its `h:` token on a destination that may not name it (#369). */
28
+ host: string;
29
+ /** ISO timestamp as written. */
30
+ at: string;
31
+ /** `m:` digest (#327), or '' on a legacy comment. */
32
+ machine: string;
33
+ }
34
+ export function encodeClaim(claim?: Partial<DecodedClaim>): string;
35
+ export function decodeClaim(body: string | null | undefined): DecodedClaim | null;
36
+
37
+ export type DecodedRelease =
38
+ | { kind: 'release'; rest: string }
39
+ | { kind: 'yield'; winner: string; rest: string };
40
+ export function encodeRelease(release?: { winner?: string; rest?: string }): string;
41
+ export function decodeRelease(body: string | null | undefined): DecodedRelease | null;
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+ /**
3
+ * CODEC (#497, epic #496): the claim/release comment WIRE FORMAT as encode/decode pairs. Pure and
4
+ * synchronous — no I/O, no clock, no requires — so it can be shared as code with any consumer that
5
+ * reads or writes the same comments. The readers built on it (which claims still stand, who wins a
6
+ * race) stay in tools/lib/claim-comments.js; the writers that need the clock, the machine id and the
7
+ * tracker stay in tools/colab and call `encodeClaim` / `encodeRelease` here.
8
+ *
9
+ * These strings are a STABLE WIRE FORMAT: the refusal path, the tie-break, and dashboards grep
10
+ * them, and an older colab on another machine parses what this one writes. `codec/samples.json`
11
+ * holds real, scrubbed comments; the test requires every one to survive encode(decode(s)) byte for
12
+ * byte. Change a byte here and that test is what tells you an older reader just broke.
13
+ */
14
+
15
+ const CLAIM_MARK = '🔒 Claimed';
16
+ const RELEASE_MARK = '✅ Released';
17
+ // Parses a claim comment body back into {worktree, branch, host, at}. The `· <host>` field is
18
+ // what lets the tie-break tell two machines of the SAME GitHub user apart. On a public destination
19
+ // it carries an opaque `h:` token instead of the raw name (#369, machine.js `hostToken`) — same
20
+ // field, same position, so this regex and every older parser read both shapes. The optional
21
+ // trailing `· session <value>` (added 2026-07) is captured separately by SESSION_RE so this regex
22
+ // stays byte-stable for session-less comments.
23
+ const CLAIM_RE = /🔒 Claimed — worktree `([^`]*)` · branch `([^`]*)` · host `([^`]*)` · (\S+)/;
24
+ // The `· session <field>` tail, captured as the rest of the line. parseSessionField() then decodes
25
+ // the THREE shapes it can take — `[name](url)`, a bare URL, or a bare name — plus the legacy
26
+ // plain-URL form written before sessionName existed.
27
+ const SESSION_RE = /· session (.+)$/;
28
+ // #327: the claimant's machine, as the public `m:` digest (tools/lib/machine.js `machineToken`),
29
+ // written AFTER the timestamp and BEFORE the session suffix — so CLAIM_RE's four groups and
30
+ // SESSION_RE's end anchor both parse a new comment exactly as they parse a legacy one, and a legacy
31
+ // comment (no such field) simply has no machine and is compared by host.
32
+ const MACHINE_RE = /· machine `(m:[0-9a-f]{12})`/;
33
+ // A yield: the loser of a race releases, naming the winner by its identity string
34
+ // (`claimIdentity.identityString` — `login@host`, or `login@host#session` under the fine setting).
35
+ const YIELD_RE = /^✅ Released \(yielded — earlier claim by (.+?) wins\)/;
36
+
37
+ /**
38
+ * Does `v` look like a session URL / `session_…` id rather than a display name? A SHAPE heuristic
39
+ * (#306), not a gate — claim-identity.js re-exports this one copy of it.
40
+ */
41
+ function looksLikeSessionId(v) {
42
+ const s = String(v == null ? '' : v).trim();
43
+ if (!s) return false;
44
+ return /^https?:\/\//.test(s) || /session_[\w-]+/.test(s);
45
+ }
46
+
47
+ /**
48
+ * Encode the `· session <field>` tail of a claim comment. Both → a markdown link; url only → the
49
+ * legacy bare form; name only → the bare name; neither → nothing.
50
+ */
51
+ function encodeSessionField(session, sessionName) {
52
+ if (sessionName && session) return ` · session [${sessionName}](${session})`;
53
+ if (session) return ` · session ${session}`;
54
+ if (sessionName) return ` · session ${sessionName}`;
55
+ return '';
56
+ }
57
+
58
+ /**
59
+ * Decode the `· session <field>` tail of a claim comment into { sessionName, session }. Accepts:
60
+ * `[name](url)` → both; bare `https://…`/`session_…` → url only; any other bare token → name.
61
+ * The bare-URL branch is exactly the LEGACY format written before sessionName existed, so old
62
+ * comments keep parsing. Returns empty strings when there is no session tail.
63
+ */
64
+ function parseSessionField(body) {
65
+ const m = String(body).match(SESSION_RE);
66
+ if (!m) return { sessionName: '', session: '' };
67
+ const v = m[1].trim();
68
+ const link = v.match(/^\[([^\]]*)\]\((.*)\)$/);
69
+ if (link) return { sessionName: link[1], session: link[2] };
70
+ if (looksLikeSessionId(v)) return { sessionName: '', session: v };
71
+ return { sessionName: v, session: '' };
72
+ }
73
+
74
+ /** `{login, host, session}` → `login@host[#session]` — the identity string a yield names. */
75
+ function encodeIdentity({ login, host, session } = {}) {
76
+ return `${login}@${host}${session ? `#${session}` : ''}`;
77
+ }
78
+
79
+ /** `login@host[#session]` → its parts. Logins cannot contain `@`, hosts cannot contain `#`. */
80
+ function parseIdentity(s) {
81
+ const str = String(s || '').trim();
82
+ const at = str.indexOf('@');
83
+ if (at <= 0) return null;
84
+ const rest = str.slice(at + 1);
85
+ const hash = rest.indexOf('#');
86
+ return {
87
+ login: str.slice(0, at),
88
+ host: hash === -1 ? rest : rest.slice(0, hash),
89
+ session: hash === -1 ? '' : rest.slice(hash + 1),
90
+ };
91
+ }
92
+
93
+ /**
94
+ * The exact claim-comment body. Every field is written as given: `worktree`/`branch` default to `-`
95
+ * ("none" — it used to be the word `trunk`, which read as a branch that never existed, #53); `at`
96
+ * is the caller's ISO timestamp (the codec holds no clock); `machine` is the `m:` digest or empty
97
+ * (#327, the field is then omitted); `host` is the raw hostname or its `h:` token, whichever the
98
+ * destination allows (#369 — deciding that is the caller's job, not the codec's).
99
+ */
100
+ function encodeClaim({ worktree, branch, host, at, machine, session, sessionName } = {}) {
101
+ const base = `${CLAIM_MARK} — worktree \`${worktree || '-'}\` · branch \`${branch || '-'}\` · host \`${host}\` · ${at}`;
102
+ const mach = machine ? ` · machine \`${machine}\`` : '';
103
+ return base + mach + encodeSessionField(session, sessionName);
104
+ }
105
+
106
+ /**
107
+ * A claim comment body → { worktree, branch, host, at, machine, session, sessionName }, or null when
108
+ * the body carries no claim. Lenient exactly where the readers always were (CLAIM_RE is unanchored,
109
+ * a legacy comment simply lacks machine/session), and lossless on what `encodeClaim` writes:
110
+ * `worktree`/`branch` keep a literal `-` rather than mapping it to empty, so the pair round-trips.
111
+ */
112
+ function decodeClaim(body) {
113
+ const str = String(body == null ? '' : body).trim();
114
+ const m = str.match(CLAIM_RE);
115
+ if (!m) return null;
116
+ const mm = str.match(MACHINE_RE);
117
+ const { session, sessionName } = parseSessionField(str);
118
+ return { worktree: m[1], branch: m[2], host: m[3], at: m[4], machine: mm ? mm[1] : '', session, sessionName };
119
+ }
120
+
121
+ /**
122
+ * A release comment body. `{}` → the plain marker (`colab release`, `worktree rm`); `{ winner }` →
123
+ * a yield naming the winner's identity string. `rest` is any text after the marker (or after the
124
+ * yield's closing parenthesis) — a hand-written release keeps its prose through a round trip.
125
+ */
126
+ function encodeRelease({ winner, rest } = {}) {
127
+ const tail = rest || '';
128
+ if (winner) return `${RELEASE_MARK} (yielded — earlier claim by ${winner} wins)${tail}`;
129
+ return RELEASE_MARK + tail;
130
+ }
131
+
132
+ /**
133
+ * A release comment body → { kind: 'yield', winner, rest } | { kind: 'release', rest }, or null when
134
+ * the body is not a release. `winner` is the raw identity string (`parseIdentity` splits it).
135
+ */
136
+ function decodeRelease(body) {
137
+ const str = String(body == null ? '' : body).trim();
138
+ if (!str.startsWith(RELEASE_MARK)) return null;
139
+ const y = str.match(YIELD_RE);
140
+ if (y) return { kind: 'yield', winner: y[1], rest: str.slice(y[0].length) };
141
+ return { kind: 'release', rest: str.slice(RELEASE_MARK.length) };
142
+ }
143
+
144
+ module.exports = {
145
+ CLAIM_MARK, RELEASE_MARK, CLAIM_RE, SESSION_RE, MACHINE_RE, YIELD_RE,
146
+ looksLikeSessionId,
147
+ encodeSessionField, parseSessionField,
148
+ encodeIdentity, parseIdentity,
149
+ encodeClaim, decodeClaim,
150
+ encodeRelease, decodeRelease,
151
+ };
@@ -0,0 +1,10 @@
1
+ // Types for tools/lib/codec (#497, epic #496) — the tracker codec. Pure and synchronous: every
2
+ // function here is a string ↔ object transform with no I/O. The wire format's spec is
3
+ // samples.json beside this file; codec.test.js pins that every runtime export is declared.
4
+
5
+ export * from './labels';
6
+ export * from './claim';
7
+ import * as labels from './labels';
8
+ import * as claim from './claim';
9
+ /** The two halves, also reachable by name: `codec.labels.decodeLabel`, `codec.claim.encodeClaim`. */
10
+ export { labels, claim };
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+ /**
3
+ * The tracker codec (#497, epic #496): everything this toolkit writes to an issue tracker with a
4
+ * meaning, as pure, synchronous encode/decode pairs — no I/O, no clock, no requires outside this
5
+ * directory — so a consumer can share it as code instead of keeping a hand copy.
6
+ *
7
+ * labels — the convention label vocabulary, plus `encodeLabel` / `decodeLabel`
8
+ * claim — the `🔒 Claimed` / `✅ Released` comment format, plus `encodeClaim` / `decodeClaim`
9
+ * and `encodeRelease` / `decodeRelease`
10
+ *
11
+ * `samples.json` beside this file is the language-neutral spec: real, scrubbed tracker strings that
12
+ * every encode(decode(s)) must reproduce byte for byte. Typed consumers: `index.d.ts`.
13
+ */
14
+ const labels = require('./labels');
15
+ const claim = require('./claim');
16
+
17
+ module.exports = { labels, claim, ...labels, ...claim };