@futurelastic/colab-handbook 1.13.0-rc.50 → 1.13.0-rc.52

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
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.13.0-rc.50"
36
+ "version": "1.13.0-rc.52"
37
37
  }
package/tools/colab CHANGED
@@ -4185,8 +4185,14 @@ TRUSTED_ASSOCIATIONS, checked on read. Same principle, a different mechanism, be
4185
4185
  command TRANSCRIBES a decision made elsewhere rather than AUTHORIZING a write that did not exist
4186
4186
  before it ran — the flag would assert nothing here that \`--ruled-by\` does not already.
4187
4187
 
4188
- \`--answers <ref>\` names the \`<!-- decision:options -->\` comment (id or URL) this decision
4189
- resolves, when one exists — omit it when there was no options block.
4188
+ \`--answers <ref>\` names the question this decision resolves: an ASK ID (the \`id=\` of an open
4189
+ \`<!-- <tool>:ask id=<id> v=<n> -->\` record a dashboard that tracks asks wrote on the issue), or the
4190
+ \`<!-- decision:options -->\` comment (id or URL). Omit it only when there is neither. --record
4191
+ reads the issue's open asks first (#582) — an ask with no answer record, and no ⚖ record
4192
+ naming it, after its latest version: with ONE open ask and no --answers it prints the ask id
4193
+ and the exact re-run line, and says the ruling will be read as answering that ask; with TWO OR
4194
+ MORE it REFUSES before any write and lists every id, because a nameless ruling cannot say which
4195
+ one it settles.
4190
4196
 
4191
4197
  Reopening removes \`${labels.DECISION_RECORDED_LABEL}\`, re-applies \`${labels.NEEDS_DECISION_LABEL}\`,
4192
4198
  and posts a \`${decisionRecord.REOPEN_MARK}\` receipt — every decision on that issue up to this
@@ -4215,7 +4221,7 @@ Options:
4215
4221
  and an issue number is present, for the common one-shot case)
4216
4222
  --reopen reopen an existing decision instead of recording a new one
4217
4223
  --ruled-by <name> required for --record/--reopen — who made this call, never the typist
4218
- --answers <ref> (--record only) the decision:options comment this answers, if any
4224
+ --answers <ref> (--record only) the open ask id, or the decision:options comment, this answers
4219
4225
  --body-file <f> ruling prose (or reopen reason) to append below the marker line
4220
4226
  --list list every issue with a live decision right now, instead of recording
4221
4227
  --json (with --list) machine-readable output
@@ -4307,6 +4313,23 @@ function cmdDecisionRecord(repoAbs, num, opts, body) {
4307
4313
  ${pair.fix}`);
4308
4314
  }
4309
4315
 
4316
+ // #582: show the recorder the asks still waiting on this issue, so the ruling names the one it
4317
+ // settles. One open ask + no --answers: a consumer reads the ruling as answering it — say so.
4318
+ // Two or more + no --answers: ambiguous, refuse before any write (same posture as the pair
4319
+ // check above) and list the ids.
4320
+ const asks = decisionRecord.openAsks(info.comments);
4321
+ const shellQuote = (v) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(String(v)) ? String(v) : `'${String(v).replace(/'/g, `'\\''`)}'`);
4322
+ if (asks.length > 0 && !opts.answers) {
4323
+ const rerun = (id) => `colab decision ${num} --record --ruled-by ${shellQuote(opts.ruledBy)} --answers ${shellQuote(id)}${opts.bodyFile ? ` --body-file ${shellQuote(opts.bodyFile)}` : ''}`;
4324
+ const rows = asks.map((a) => ` ${a.id} (v${a.version}, asked ${a.at || 'unknown'})\n ${rerun(a.id)}`).join('\n');
4325
+ if (asks.length > 1) {
4326
+ throw new UserError(`#${num} has ${asks.length} open asks and this record names none — a reader cannot tell which one the ruling settles. Re-run with --answers <ask id>:
4327
+ ${rows}`);
4328
+ }
4329
+ warn(`#${num} has one open ask: ${asks[0].id} (v${asks[0].version}, asked ${asks[0].at || 'unknown'}). This ruling will be read as answering it. To name it explicitly, re-run as:
4330
+ ${rerun(asks[0].id)}`);
4331
+ }
4332
+
4310
4333
  const present = git.ghListLabels(repoAbs);
4311
4334
  if (present && !present.includes(labels.DECISION_RECORDED_LABEL)) {
4312
4335
  throw new UserError(labels.decisionRecordedMissingLabelHint(present)
@@ -10566,6 +10589,11 @@ It never waits: each call reads the remote, takes ONE step and exits —
10566
10589
  One batch per base: a batch at this base carrying OTHER members is waited on (exit 3) while its run
10567
10590
  is pending or green, but a declined one — its combined run red — is deleted and the batch you asked
10568
10591
  for is built in its place, so the survivors of a decline can batch without landing serially first (#391).
10592
+ The batch also holds the trunk LANE (#581): while a ship-batch/<trunk-sha7> ref at trunk's tip has its
10593
+ combined run in flight — or green within ${shipBatch.LANE_GRACE_SEC / 60}m, so its lander can land it — a serial
10594
+ \`colab ship --branch\` into trunk pauses with exit 3 (⏸ BATCH-IN-FLIGHT; its --dry --json row
10595
+ 'no batch in flight (#581)' reads self-clearing) instead of moving trunk under it and discarding the run.
10596
+ A red batch, or one with no run / not landed past that grace, holds nothing.
10569
10597
  A member that conflicts with the members already in is dropped to the next batch; the rest go on —
10570
10598
  unless every conflicting path is generated (defaults + project.yml generated:): then .colab/hooks/pre-ship
10571
10599
  regenerates them on the combined head and the member stays in (#387). No hook, or a failing one → dropped.
@@ -12216,6 +12244,17 @@ function cmdShipDryJson(opts) {
12216
12244
  if (coreReviewJson.verdict === 'pending') mode = 'pr-pending';
12217
12245
  }
12218
12246
 
12247
+ // #581: the same lane read as the prose path's table — a squash into trunk while a batch holds the
12248
+ // lane would discard the batch's run. SELF_CLEARING: the batch lands or is declined on its own.
12249
+ // Never for a batch member read (the batch IS the lane) nor for evidence-close (trunk does not move).
12250
+ if (!dryMode.evidenceClose && !opts._batchMember) {
12251
+ const laneJson = shipBatchLaneCheck(repoAbs, doc, trunk, target, gh);
12252
+ if (laneJson) {
12253
+ checks.push({ name: 'no batch in flight (#581)', ok: !laneJson.held, class: laneJson.held ? SELF_CLEARING : null,
12254
+ detail: laneJson.detail, ...(laneJson.held ? { batchRef: laneJson.ref } : {}) });
12255
+ }
12256
+ }
12257
+
12219
12258
  // #149: the same inherited-closing-keyword scan the prose --dry path runs, mirrored here —
12220
12259
  // following #153's own precedent for this function (its comment above: "a caller reading only
12221
12260
  // checks[]/ok … used to see NO check at all here"). Without this, the ONE caller class this path
@@ -13300,6 +13339,11 @@ function cmdShip(argv) {
13300
13339
  const coreReview = shipCoreReview(repoAbs, gh, target, sess.branch);
13301
13340
  const coreOk = coreReview.verdict !== 'refuse';
13302
13341
  checks.push([coreOk ? (coreReview.verdict === 'pending' ? '⏸' : '✓') : '✗', 'core-path review (#350)', coreReview.detail]);
13342
+
13343
+ // #581: a batch in flight at trunk's tip holds the lane. Like the core-path review's 'pending', a
13344
+ // hold is not a failed precondition — it is a pause, taken below once every real one has passed.
13345
+ const lane = shipBatchLaneCheck(repoAbs, doc, trunk, target, gh);
13346
+ if (lane) checks.push([lane.held ? '⏸' : '✓', 'no batch in flight (#581)', lane.detail]);
13303
13347
  for (const w of coreReview.warnings) warn(`${coreReview.codeownersPath}: ${w}`);
13304
13348
 
13305
13349
  // #389: the record this ship will write after the push must be writable NOW.
@@ -13534,6 +13578,8 @@ function cmdShip(argv) {
13534
13578
  print(' Plan: no merge, no commit, no push · post evidence comment + CLOSE each issue · ' +
13535
13579
  (opts.keepWorktree ? 'keep worktree' : 'worktree rm') + ' (releases claims)');
13536
13580
  print(' Gate: every closing issue must already carry an evidence comment — checked at run time.');
13581
+ } else if (lane && lane.held && coreReview.verdict !== 'pending') {
13582
+ print(` Plan: PAUSE (⏸ exit 3, nothing merged) — ${lane.ref} holds the ${trunk} lane (#581); run again once it has landed or been declined`);
13537
13583
  } else if (coreReview.verdict === 'pending') {
13538
13584
  print(` Plan: push ${sess.branch} · ${coreReview.pr ? `PR #${coreReview.pr.number} already open` : 'open a PR → ' + target} · ` +
13539
13585
  'PAUSE (⏸ exit 3, no squash) until an account other than the author approves the current head (#350)');
@@ -13599,6 +13645,9 @@ function cmdShip(argv) {
13599
13645
  return shipOpenCorePr(repoAbs, coreReview, { target, branch: sess.branch, title, body });
13600
13646
  }
13601
13647
 
13648
+ // ---- (b5) #581: a batch holds the trunk lane — pause before B0, so nothing is synced or merged ----
13649
+ if (lane && lane.held) { printBatchLanePause(lane, trunk); return 3; }
13650
+
13602
13651
  // ---- (c) B0: merge the TARGET into the branch (in the worktree, or an ephemeral one) ----
13603
13652
  const generated = [...DEFAULT_GENERATED, ...(Array.isArray(doc.generated) ? doc.generated.map(String) : [])];
13604
13653
  const hasPreShip = fs.existsSync(path.join(repoAbs, '.colab', 'hooks', 'pre-ship'));
@@ -13744,6 +13793,10 @@ function cmdShip(argv) {
13744
13793
  ciGrantForTrailer = ciResultB1.grantVerdict;
13745
13794
  }
13746
13795
  }
13796
+ // #581: re-read the lane right before the merge — B0 sits between the table and here, and a batch
13797
+ // built in that window is exactly as live as one the table saw.
13798
+ const laneB1 = lane ? shipBatchLaneCheck(repoAbs, doc, trunk, target, gh) : null;
13799
+ if (laneB1 && laneB1.held) { cleanupEphemeral(); printBatchLanePause(laneB1, trunk); return 3; }
13747
13800
  // WHERE the squash happens. Into trunk it is the main checkout, which is on trunk by invariant
13748
13801
  // (and was just verified to be). Into a declared line it must NOT be: checking the main checkout
13749
13802
  // out onto a long-lived line is the very state that made this axis necessary — everything reading
@@ -14266,6 +14319,46 @@ function shipDryJsonReport(opts) {
14266
14319
  return { ok: code === 0, body: holder.body || null, error: null };
14267
14320
  }
14268
14321
 
14322
+ /**
14323
+ * #581: is a batch in flight at trunk's current tip? Read by every serial door that moves trunk (the
14324
+ * prose ship's table and B1, `--dry --json`), so a lander told about it waits instead of moving trunk
14325
+ * under the batch — which would throw the batch's green combined run away. The rule is
14326
+ * lib/ship-batch.js laneHold; this only reads the remote.
14327
+ *
14328
+ * Inert (null, no git or gh call) unless project.yml declares ship-batch > 1, the merge target is
14329
+ * trunk, and gh is usable. Out: null, or `{ held, ref, why, released, detail }`.
14330
+ */
14331
+ function shipBatchLaneCheck(repoAbs, doc, trunk, target, gh) {
14332
+ if (target !== trunk || !gh || shipBatch.parseShipBatch(doc).n <= 1) return null;
14333
+ const remote = git.remoteFor(repoAbs);
14334
+ const ls = git.git(['ls-remote', remote, `refs/heads/${trunk}`, 'refs/heads/ship-batch/*'], repoAbs);
14335
+ if (!ls.ok) return { held: false, released: [], detail: `could not read ${remote} — no batch provably in flight` };
14336
+ const rows = ls.stdout.split('\n').map((l) => l.split('\t')).filter(([sha, ref]) => sha && ref);
14337
+ const trunkNow = ((rows.find(([, ref]) => ref.trim() === `refs/heads/${trunk}`) || [])[0] || '').trim();
14338
+ const atTip = rows.map(([sha, ref]) => ({ sha: sha.trim(), parsed: shipBatch.parseBatchRef(ref.trim()) }))
14339
+ .filter((x) => x.parsed && trunkNow.startsWith(x.parsed.base7));
14340
+ const batches = atTip.map((x) => {
14341
+ const runs = git.ghRunsForRef(repoAbs, x.parsed.ref, x.sha);
14342
+ let t = git.git(['log', '-1', '--format=%cI', x.sha], repoAbs);
14343
+ if (!t.ok) { git.git(['fetch', '-q', remote, `refs/heads/${x.parsed.ref}`], repoAbs); t = git.git(['log', '-1', '--format=%cI', x.sha], repoAbs); }
14344
+ const built = t.ok ? Date.parse(t.stdout.trim()) : NaN;
14345
+ return { ref: x.parsed.ref, base7: x.parsed.base7, verdict: shipBatch.combinedVerdict(runs),
14346
+ builtAtMs: Number.isFinite(built) ? built : null, settledAtMs: shipBatch.settledAt(runs) };
14347
+ });
14348
+ const r = shipBatch.laneHold({ batches, trunkNow, nowMs: Date.now() });
14349
+ const detail = r.held
14350
+ ? `${r.ref} holds the ${trunk} lane — ${r.why}; landing now would move ${trunk} under it and discard its run`
14351
+ : (r.released.length ? `no batch holds the lane (${r.released.map((x) => `${x.ref}: ${x.why}`).join('; ')})` : `no batch in flight at ${trunk}@${shortSha(trunkNow)}`);
14352
+ return { ...r, trunkNow, detail };
14353
+ }
14354
+
14355
+ /** #581: the pause a serial ship takes while a batch holds the trunk lane — one message, every door. */
14356
+ function printBatchLanePause(lane, trunk) {
14357
+ print(`⏸ BATCH-IN-FLIGHT ${lane.ref} — ${lane.why}. Nothing landed.`);
14358
+ print(` Landing now would move ${trunk} under it and throw its combined run away (#581). Wait for it to land`);
14359
+ print(' or be declined (bounded, B1a — the same wait as any CI run), then run this command again.');
14360
+ }
14361
+
14269
14362
  function cmdShipBatch(opts) {
14270
14363
  for (const [key, flag] of [['direct', '--direct'], ['worktree', '--worktree'], ['branch', '--branch'], ['message', '--message'], ['refs', '--refs'], ['adopt', '--adopt'], ['json', '--json']]) {
14271
14364
  if (opts[key]) throw new UserError(`--batch does not combine with ${flag} — each member ships with its own recorded claims and composed message (#373)`);
@@ -27,3 +27,10 @@ export const OPTIONS_RE: RegExp;
27
27
  export const MOCKUP_RE: RegExp;
28
28
  export function encodeMockup(url: string): string;
29
29
  export function mockupUrls(body: unknown): string[];
30
+
31
+ /** An ask record a dashboard that tracks asks wrote (#582) — read-only to colab. */
32
+ export interface AskRecord { ns: string; id: string; version: number; index: number; }
33
+ /** An answer record naming an ask by id (#582). */
34
+ export interface AnswerRecord { ns: string; ask: string; version: number | null; index: number; }
35
+ export function askRecords(text: unknown): AskRecord[];
36
+ export function answerRecords(text: unknown): AnswerRecord[];
@@ -74,8 +74,62 @@ function mockupUrls(body) {
74
74
  return out;
75
75
  }
76
76
 
77
+ /**
78
+ * ASK / ANSWER RECORDS (#582) — the structured question a dashboard that tracks asks writes onto an
79
+ * issue, and the answer that settles it. READ-ONLY here: colab never writes either, it only needs to
80
+ * know which asks are still open so `colab decision --record` can name the one a ruling settles.
81
+ *
82
+ * Wire shape, namespaced by whatever tool wrote it (the namespace is not interpreted — any tool
83
+ * writing this shape is read the same way):
84
+ * `<!-- <tool>:ask id=<id> v=<n> [key=value …] -->` + the question below it
85
+ * `<!-- <tool>:answer ask=<id> [v=<n>] [key=value …] -->` (+ optional note)
86
+ * and the same heads as a bare line form `<tool>:ask id=…` at the start of a line. Attribute values
87
+ * are percent-encoded and space-separated. Other kinds naming an ask (a wait, a delegation) are not
88
+ * answers and are not read.
89
+ */
90
+ const RECORD_NS = '[a-z][a-z0-9_-]*';
91
+ function recordHeads(text, kind) {
92
+ if (typeof text !== 'string' || text === '') return [];
93
+ const heads = [];
94
+ const markerRe = new RegExp(`<!--\\s*(${RECORD_NS}):${kind}\\s+([^>]*?)\\s*-->`, 'g');
95
+ const lineRe = new RegExp(`^(${RECORD_NS}):${kind}\\s+([^\\n]*)$`, 'gm');
96
+ for (const re of [markerRe, lineRe]) {
97
+ let m;
98
+ while ((m = re.exec(text))) {
99
+ const attrs = parseRecordAttrs(m[2]);
100
+ if (attrs) heads.push({ index: m.index, ns: m[1], attrs });
101
+ }
102
+ }
103
+ return heads.sort((a, b) => a.index - b.index);
104
+ }
105
+ /** `k=v k2=v2` → `{k: v, k2: v2}` (values percent-decoded), or null when any token is not `k=v`. */
106
+ function parseRecordAttrs(raw) {
107
+ const out = {};
108
+ const toks = String(raw).trim().split(/\s+/).filter(Boolean);
109
+ if (toks.length === 0) return null;
110
+ for (const t of toks) {
111
+ const m = /^([a-z][a-z0-9_-]*)=(\S*)$/i.exec(t);
112
+ if (!m) return null;
113
+ try { out[m[1]] = decodeURIComponent(m[2]); } catch (_) { out[m[1]] = m[2]; }
114
+ }
115
+ return out;
116
+ }
117
+ /** Every ask record in `text`, in order: `{ns, id, version, index}`. Requires `id` and an integer `v >= 1`. */
118
+ function askRecords(text) {
119
+ return recordHeads(text, 'ask')
120
+ .filter((h) => h.attrs.id && /^\d+$/.test(h.attrs.v || '') && Number(h.attrs.v) >= 1)
121
+ .map((h) => ({ ns: h.ns, id: h.attrs.id, version: Number(h.attrs.v), index: h.index }));
122
+ }
123
+ /** Every answer record in `text`, in order: `{ns, ask, version, index}` (`version` null when absent). */
124
+ function answerRecords(text) {
125
+ return recordHeads(text, 'answer')
126
+ .filter((h) => h.attrs.ask)
127
+ .map((h) => ({ ns: h.ns, ask: h.attrs.ask, version: /^\d+$/.test(h.attrs.v || '') ? Number(h.attrs.v) : null, index: h.index }));
128
+ }
129
+
77
130
  module.exports = {
78
131
  DECISION_MARK, REOPEN_MARK, DECISION_RE, REOPEN_RE,
79
132
  encodeDecision, decodeDecision, encodeReopen, decodeReopen,
80
133
  OPTIONS_RE, MOCKUP_RE, encodeMockup, mockupUrls,
134
+ askRecords, answerRecords,
81
135
  };
@@ -300,6 +300,47 @@ function evaluateIssue({ labels, comments, labelEvents = null, body, trust } = {
300
300
  return { recorded, gated, contradiction: recorded && gated, pair, pending, decisions, ask, unshapedAsk };
301
301
  }
302
302
 
303
+ /**
304
+ * #582: the ask records on this issue still waiting on an answer — what `colab decision --record`
305
+ * shows the recorder, so the ruling can name the ask it settles (`--answers <id>`). A consumer that
306
+ * tracks asks reads a nameless ruling as answering the issue's ONLY open ask; with two or more it
307
+ * cannot tell which one the ruling meant.
308
+ *
309
+ * An ask is OPEN when no answer comes AFTER its latest ask record (same id; a re-ask at a higher
310
+ * version reopens it). An answer is either an answer record naming the id, or a live `⚖ Decision
311
+ * recorded` whose `answers` field is that id. Order is by `createdAt`, then position inside one
312
+ * comment. Deliberately NOT trust-filtered: this only decides what to SHOW and whether a nameless
313
+ * record is ambiguous — it gates no start and authorizes nothing.
314
+ *
315
+ * Returns [{id, version, at, ns}], oldest-asked first.
316
+ */
317
+ function openAsks(comments) {
318
+ const list = Array.isArray(comments) ? comments : [];
319
+ const sorted = list
320
+ .map((c, i) => ({ c, i }))
321
+ .sort((a, b) => (a.c.createdAt < b.c.createdAt ? -1 : a.c.createdAt > b.c.createdAt ? 1 : a.i - b.i));
322
+ const asks = new Map(); // id -> {id, version, at, ns, pos}
323
+ const answers = []; // {id, pos}
324
+ sorted.forEach(({ c }, ci) => {
325
+ const body = String(c.body || '');
326
+ for (const a of codec.askRecords(body)) {
327
+ asks.set(a.id, { id: a.id, version: a.version, at: c.createdAt || null, ns: a.ns, pos: [ci, a.index] });
328
+ }
329
+ for (const r of codec.answerRecords(body)) answers.push({ id: r.ask, pos: [ci, r.index] });
330
+ });
331
+ const live = new Set(liveDecisions(list).map((d) => d.at));
332
+ sorted.forEach(({ c }, ci) => {
333
+ if (!live.has(c.createdAt)) return;
334
+ const d = codec.decodeDecision(c.body);
335
+ if (d && d.answers && d.answers !== '-') answers.push({ id: d.answers, pos: [ci, 0] });
336
+ });
337
+ const after = (p, q) => p[0] > q[0] || (p[0] === q[0] && p[1] > q[1]);
338
+ return [...asks.values()]
339
+ .filter((a) => !answers.some((r) => r.id === a.id && after(r.pos, a.pos)))
340
+ .sort((a, b) => (after(a.pos, b.pos) ? 1 : -1))
341
+ .map(({ id, version, at, ns }) => ({ id, version, at, ns }));
342
+ }
343
+
303
344
  module.exports = {
304
345
  DECISION_MARK, REOPEN_MARK, DECISION_RE, REOPEN_RE,
305
346
  decisionCommentBody, reopenCommentBody,
@@ -308,4 +349,5 @@ module.exports = {
308
349
  OPTIONS_RE, PAIR_VERDICTS, pairVerdict,
309
350
  MOCKUP_RE, mockupUrls, ASK_SHAPES, askShape,
310
351
  evaluateIssue,
352
+ openAsks,
311
353
  };
package/tools/lib/git.js CHANGED
@@ -1042,7 +1042,7 @@ function ghInstalled() {
1042
1042
  function ghRunsForRef(repo, ref, sha, limit = 20) {
1043
1043
  if (!sha) return null;
1044
1044
  const r = gh(['run', 'list', '--branch', ref, '-L', String(limit),
1045
- '--json', 'headSha,status,conclusion,createdAt,databaseId,workflowName,attempt'], { cwd: repo });
1045
+ '--json', 'headSha,status,conclusion,createdAt,updatedAt,databaseId,workflowName,attempt'], { cwd: repo });
1046
1046
  if (!r.ok) return null;
1047
1047
  let runs;
1048
1048
  try { runs = JSON.parse(r.stdout); } catch (_) { return null; }
@@ -370,6 +370,66 @@ function batchGreenCoversTrunk({ trunkRows, batchRows, trunkFires, batchFires })
370
370
  return (batchRows || []).length >= a.length;
371
371
  }
372
372
 
373
+ /**
374
+ * #581: the lane reservation. A batch ref at trunk's CURRENT tip whose combined run is in flight (or
375
+ * green and not yet landed) holds the trunk lane: a serial `colab ship` into trunk that landed now
376
+ * would move trunk under it, and the batch's next call would throw the green run away and rebuild —
377
+ * measured five builds in two hours on one repo, every member ready the whole time. The ref itself
378
+ * is the reservation: it already sits on the remote every lander reads, it names its base, and its
379
+ * runs say whether it is alive. No second record to write, expire or keep in sync.
380
+ *
381
+ * Facts in, per batch ref on the remote (`batches`):
382
+ * ref, base7 parseBatchRef
383
+ * verdict combinedVerdict of the runs at its head
384
+ * builtAtMs the batch head's commit time (the build commits it), null = unread
385
+ * settledAtMs the newest `updatedAt` of its runs once green, null = unread
386
+ * plus `trunkNow` (the remote trunk sha), `nowMs`, and `graceSec`.
387
+ *
388
+ * Out: `{ held: true, ref, why }` for the first batch that holds the lane, else `{ held: false,
389
+ * released: [{ ref, why }] }` naming each batch at this base that does NOT hold it, and why.
390
+ * - a batch on an older base holds nothing: trunk already moved past it, it rebuilds anyway;
391
+ * - red (first attempt or after its re-run) → declined, holds nothing;
392
+ * - pending, or a run list that could not be read → held (fail closed: a pause clears itself);
393
+ * - no run yet → held for `graceSec` after it was built, then released (its run never came);
394
+ * - green → held for `graceSec` after it went green — its lander lands it on its next call —
395
+ * then released: a green batch nobody lands is abandoned, and must not hold the lane forever.
396
+ * An unread time (built/settled) is released, never held: a hold has to be provably alive.
397
+ */
398
+ const LANE_GRACE_SEC = 900;
399
+
400
+ function laneHold({ batches, trunkNow, nowMs, graceSec = LANE_GRACE_SEC } = {}) {
401
+ const now = String(trunkNow || '');
402
+ const released = [];
403
+ if (!now) return { held: false, released };
404
+ const fresh = (atMs) => Number.isFinite(atMs) && Number.isFinite(nowMs) && (nowMs - atMs) < graceSec * 1000;
405
+ const mins = (atMs) => `${Math.max(0, Math.round((nowMs - atMs) / 60000))}m ago`;
406
+ for (const b of (Array.isArray(batches) ? batches : [])) {
407
+ if (!b || !b.base7 || !now.startsWith(b.base7)) continue;
408
+ const v = b.verdict || { state: 'pending', why: 'the run list could not be read' };
409
+ if (v.state === 'red') { released.push({ ref: b.ref, why: `declined — ${v.why}` }); continue; }
410
+ if (v.state === 'pending') return { held: true, ref: b.ref, why: `combined run in flight (${v.why})` };
411
+ if (v.state === 'none') {
412
+ if (fresh(b.builtAtMs)) return { held: true, ref: b.ref, why: `built ${mins(b.builtAtMs)}, its combined run has not appeared yet` };
413
+ released.push({ ref: b.ref, why: Number.isFinite(b.builtAtMs)
414
+ ? `no combined run ${mins(b.builtAtMs)} after it was built (grace ${graceSec}s) — treated as abandoned`
415
+ : 'no combined run, and its build time could not be read — not provably alive' });
416
+ continue;
417
+ }
418
+ if (fresh(b.settledAtMs)) return { held: true, ref: b.ref, why: `combined run green ${mins(b.settledAtMs)} — its lander lands it on its next call` };
419
+ released.push({ ref: b.ref, why: Number.isFinite(b.settledAtMs)
420
+ ? `combined run green ${mins(b.settledAtMs)} and still not landed (grace ${graceSec}s) — treated as abandoned`
421
+ : 'combined run green, but when it went green could not be read — not provably alive' });
422
+ }
423
+ return { held: false, released };
424
+ }
425
+
426
+ /** #581: when a batch's combined run settled — the newest `updatedAt` among its finished rows, else null. */
427
+ function settledAt(rows) {
428
+ const t = (Array.isArray(rows) ? rows : []).filter((r) => r && r.status === 'completed')
429
+ .map((r) => Date.parse(r.updatedAt || '')).filter(Number.isFinite);
430
+ return t.length ? Math.max(...t) : null;
431
+ }
432
+
373
433
  /**
374
434
  * #415: branches the command line names that a staged batch does not carry, in command-line order.
375
435
  * `staged` is parseMemberTrailers' `[{ branch }]`. Not a refusal on its own: a branch over the cap or
@@ -430,4 +490,5 @@ module.exports = {
430
490
  droppedTrailer, parseDroppedTrailers, appendTrailers,
431
491
  branchCiClass, memberEligibility, selectMembers, wiring, combinedVerdict, nextStep, foreignBatchStep,
432
492
  batchGreenCoversTrunk, evidenceSuffix, serialLine, notStaged, landPushFailure,
493
+ LANE_GRACE_SEC, laneHold, settledAt,
433
494
  };