@futurelastic/colab-handbook 1.22.0-rc.1 → 1.22.0-rc.3

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.22.0-rc.1"
36
+ "version": "1.22.0-rc.3"
37
37
  }
package/tools/colab CHANGED
@@ -581,8 +581,9 @@ function localClaimConflicts(st, repoAbs, nums, wtName) {
581
581
  /**
582
582
  * #325 — the claim record every machine can read, whatever the tracker: a branch on the remote whose
583
583
  * name carries the issue number (CONVENTIONS.md §4 puts the numbers in the trailing run), or — since
584
- * #550 — the claim ref `refs/claims/<branch>` that `colab worktree new` pushes the moment it cuts
585
- * (a ref no CI trigger watches; the branch itself follows at code-wrap). Asked of the remote directly (`ls-remote`, no fetch), so a
584
+ * #741 — the claim LOCK `refs/heads/claim/<N>` that `colab worktree new` and `colab claim` take (a
585
+ * `[skip ci]` commit; the branch itself follows at code-wrap), or a legacy claim ref
586
+ * `refs/claims/<branch>` an older cut left (#550, still read). Asked of the remote directly (`ls-remote`, no fetch), so a
586
587
  * clone that has never fetched sees exactly what a fresh one would.
587
588
  *
588
589
  * `mode`:
@@ -619,7 +620,89 @@ function remoteClaimConflicts(st, repoAbs, nums) {
619
620
  if (!carried.length || ours(h.branch)) continue;
620
621
  for (const num of carried) conflicts.push({ num, remote, branch: h.branch, sha: h.sha, claimRef: !!h.claimRef });
621
622
  }
622
- return { mode: 'ok', remote, conflicts };
623
+ // #741: the lock, `refs/heads/claim/<N>`. Ours when (a) this machine's own claim record holds that
624
+ // exact lock — the ONLY test for a lock colab wrote, because two colab homes on one host share the
625
+ // hardware and a `Machine:` line would read each other's locks as their own; or (b) another tool
626
+ // wrote it (no `Claimed-By: colab`) naming THIS machine — an orchestrator holding the issue for the
627
+ // session it spawned here, which that session adopts instead of being refused by its own lock.
628
+ // A lock whose commit cannot be read is foreign: fail closed, like an unreachable remote.
629
+ const ownLocks = [];
630
+ for (const l of heads.locks || []) {
631
+ if (!want.has(l.issue)) continue;
632
+ const rec = (st.claims || {})[claimKey(repoAbs, l.issue)];
633
+ const recSha = rec && rec.lock && rec.lock.sha ? String(rec.lock.sha) : '';
634
+ if (recSha && machine.isLocal(rec) && (l.fullSha.startsWith(recSha) || recSha.startsWith(l.fullSha))) {
635
+ ownLocks.push({ num: l.issue, sha: l.fullSha, adopted: !!rec.lock.adopted });
636
+ continue;
637
+ }
638
+ const read = git.readClaimLock(repoAbs, remote, l.issue, l.fullSha);
639
+ const tr = read.ok ? read.trailers : {};
640
+ if (read.ok && !tr.colab && tr.machine && branchName.machineLabel(tr.machine) === branchName.machineLabel(HOST)) {
641
+ ownLocks.push({ num: l.issue, sha: l.fullSha, adopted: true, writer: tr.author || null });
642
+ continue;
643
+ }
644
+ conflicts.push({ num: l.issue, remote, lock: true, sha: l.sha, fullSha: l.fullSha,
645
+ branch: tr.branch || null, machine: tr.machine || null, writer: tr.colab ? 'colab' : (tr.author || null),
646
+ unread: read.ok ? null : String(read.stderr || '').split('\n')[0] });
647
+ }
648
+ return { mode: 'ok', remote, conflicts, ownLocks };
649
+ }
650
+
651
+ /**
652
+ * #741 — take the claim locks `refs/heads/claim/<N>` for `nums`, after `remoteClaimConflicts` ran.
653
+ * Locks already ours (`check.ownLocks`) are kept, not re-pushed; a foreign lock is overwritten only
654
+ * under `--force` (its observed sha becomes the lease), and everything else is created in ONE atomic
655
+ * create-only push. `{ ok, locks: { N: { ref, sha, adopted? } }, taken: [N], stderr? }`; no remote →
656
+ * `{ ok: true, locks: {}, taken: [] }` (the local record is the whole truth there).
657
+ */
658
+ function takeClaimLocksFor(repoAbs, check, nums, { branch = null, session = '', force = false } = {}) {
659
+ if (!check || check.mode !== 'ok' || !check.remote || !nums.length) return { ok: true, locks: {}, taken: [] };
660
+ const locks = {};
661
+ for (const o of check.ownLocks || []) {
662
+ if (nums.includes(o.num)) locks[o.num] = { ref: git.claimLockRef(o.num), sha: o.sha, ...(o.adopted ? { adopted: true } : {}) };
663
+ }
664
+ const expect = {};
665
+ if (force) for (const c of check.conflicts || []) if (c.lock && c.fullSha) expect[c.num] = c.fullSha;
666
+ const toTake = nums.filter((n) => !locks[n]);
667
+ if (!toTake.length) return { ok: true, locks, taken: [] };
668
+ const message = git.claimLockMessage({
669
+ nums: toTake, branch, machine: branchName.machineLabel(HOST), machineId: machine.machineToken(myMachineId()) || '', session,
670
+ });
671
+ const commit = git.makeClaimLockCommit(repoAbs, message);
672
+ if (!commit.ok) return { ok: false, locks, taken: [], stderr: commit.stderr };
673
+ const push = git.takeClaimLocks(repoAbs, check.remote, toTake, commit.sha, { expect });
674
+ if (!push.ok) return { ok: false, locks, taken: [], rejected: push.rejected, stderr: push.stderr };
675
+ for (const n of toTake) locks[n] = { ref: git.claimLockRef(n), sha: commit.sha };
676
+ return { ok: true, locks, taken: toTake };
677
+ }
678
+
679
+ /**
680
+ * #741 — release the claim locks the given claim records hold, each only while it still points at
681
+ * the recorded sha (`git.releaseClaimLock`). Best effort, like the legacy claim-ref delete beside it:
682
+ * a failure warns with the command and undoes nothing. An adopted lock (an orchestrator's) is
683
+ * released too — release is unconditional (CONVENTIONS.md §5), and a lock left behind would refuse
684
+ * every other machine on that issue.
685
+ */
686
+ function releaseClaimLocksOf(repoAbs, claims) {
687
+ const held = (claims || []).filter((c) => c && c.lock && c.lock.sha);
688
+ if (!held.length) return;
689
+ let remote = null;
690
+ try { remote = git.claimRemote(repoAbs); } catch { remote = null; }
691
+ if (!remote) return;
692
+ for (const c of held) {
693
+ const num = normIssueNum(c.issue);
694
+ const ref = git.claimLockRef(num);
695
+ const r = git.releaseClaimLock(repoAbs, remote, num, c.lock.sha);
696
+ if (r.ok && r.moved) print(` claim lock ${remote} ${ref} now points at ${r.now} — someone else's; left in place`);
697
+ else if (r.ok && !r.absent) print(` released claim lock ${remote} ${ref}`);
698
+ else if (!r.ok) warnDeferred(`could not release claim lock ${remote} ${ref} (${String(r.stderr || '').split('\n')[0]}) — delete it by hand: git push ${remote} --delete ${ref}`);
699
+ }
700
+ }
701
+
702
+ /** The refusal/stale lines for a foreign lock (#741). */
703
+ function lockHolderText(c) {
704
+ const who = [c.branch ? `branch ${c.branch}` : null, c.machine ? `machine ${c.machine}` : null, c.writer && c.writer !== 'colab' ? `written by ${c.writer}` : null].filter(Boolean).join(' · ');
705
+ return `claim lock ${c.remote} ${git.claimLockRef(c.num)} @ ${c.sha}${who ? ` (${who})` : ''}${c.unread ? ` (holder unreadable: ${c.unread})` : ''}`;
623
706
  }
624
707
 
625
708
  /** The fail-closed refusal for an unreadable remote (#325) — no override: nothing can be checked. */
@@ -726,12 +809,21 @@ function ghClaimConflicts(repoAbs, nums, myLogin, myHost, mySession, comps, myMa
726
809
  function printRefusal(localConf, ghConf, remoteConf = []) {
727
810
  process.stderr.write('✗ Refusing — one or more issues are already claimed:\n');
728
811
  for (const c of remoteConf) {
729
- process.stderr.write(c.claimRef
812
+ process.stderr.write(c.lock
813
+ ? ` #${c.num} remote: ${lockHolderText(c)} holds it, and it is not this machine's (#741)\n`
814
+ : c.claimRef
730
815
  ? ` #${c.num} remote: claim ref ${c.remote} ${git.claimRef(c.branch)} @ ${c.sha} carries it (branch not pushed yet), and it is not this machine's (#325, #550)\n`
731
816
  : ` #${c.num} remote: branch ${c.remote}/${c.branch} @ ${c.sha} carries it, and it is not this machine's (#325)\n`);
732
817
  }
733
- if (remoteConf.length) {
734
- const c = remoteConf[0];
818
+ const lockConf = remoteConf.filter((c) => c.lock);
819
+ if (lockConf.length) {
820
+ const c = lockConf[0];
821
+ process.stderr.write(` The lock IS the claim — continue that work rather than open a second one${c.branch ? `: on its machine, or once its branch is pushed: git fetch ${c.remote} ${c.branch} && git worktree add <path> ${c.branch}` : ''}\n`);
822
+ process.stderr.write(` A lock whose session is gone is stale — delete it: git push ${c.remote} --delete ${git.claimLockRef(c.num)}\n`);
823
+ }
824
+ const branchConf = remoteConf.filter((c) => !c.lock);
825
+ if (branchConf.length) {
826
+ const c = branchConf[0];
735
827
  process.stderr.write(` That ${c.claimRef ? 'claim ref' : 'branch'} IS the claim — continue it rather than open a second one:\n`);
736
828
  process.stderr.write(c.claimRef
737
829
  ? ` git fetch ${c.remote} ${git.claimRef(c.branch)}:refs/heads/${c.branch} && git worktree add <path> ${c.branch}\n`
@@ -774,6 +866,7 @@ function halfClaimText(c) {
774
866
  /** Announce exactly what --force overrides (a takeover is visible, never silent). */
775
867
  function printTakeover(localConf, ghConf, remoteConf = []) {
776
868
  for (const c of remoteConf) {
869
+ if (c.lock) { print(` --force: taking over #${c.num} although ${lockHolderText(c)} holds it (not this machine's) — the lock is overwritten`); continue; }
777
870
  print(` --force: taking over #${c.num} although ${c.claimRef ? `claim ref ${c.remote} ${git.claimRef(c.branch)}` : `branch ${c.remote}/${c.branch}`} @ ${c.sha} carries it (not this machine's)`);
778
871
  }
779
872
  for (const c of localConf) {
@@ -856,6 +949,7 @@ function yieldIssue(repoAbs, num, winner, myLogin, session = null) {
856
949
  }
857
950
  const rc = git.ghIssueComment(repoAbs, num, claimComments.yieldReleaseBody(winner, { redact: !commentHostDecision(repoAbs).include }));
858
951
  if (!rc.ok) warn(`could not post yield comment on #${num} (${rc.stderr.split('\n')[0] || rc.code})`);
952
+ let yieldedLock = null;
859
953
  let placeOutcome = null;
860
954
  state.mutate((st) => {
861
955
  const key = claimKey(repoAbs, num);
@@ -869,6 +963,7 @@ function yieldIssue(repoAbs, num, winner, myLogin, session = null) {
869
963
  } else {
870
964
  const wtName = c.worktree;
871
965
  const claimSession = c.session || session || null;
966
+ if (c.lock) yieldedLock = { issue: c.issue, lock: c.lock };
872
967
  delete st.claims[key];
873
968
  // #312, the sharpest of the three leaks this fixed: `cmdClaim` has ALREADY acquired the
874
969
  // checkout hold by the time the tie-break decides this session lost the race, so before this
@@ -887,6 +982,7 @@ function yieldIssue(repoAbs, num, winner, myLogin, session = null) {
887
982
  }
888
983
  }
889
984
  });
985
+ if (yieldedLock) releaseClaimLocksOf(repoAbs, [yieldedLock]); // #741: the lock goes with the yielded claim
890
986
  if (placeOutcome && placeOutcome.released) {
891
987
  print(` released the checkout place-claim on ${placeOutcome.rec.path}` +
892
988
  (placeOutcome.reason === 'lapsed-dead' ? ' (its holder was already gone)' : ' (this was the last claim holding it)'));
@@ -940,9 +1036,12 @@ function commentAndTieBreak(repoAbs, nums, owner) {
940
1036
  const HELP_CLAIM = `colab claim <issue> [<issue> ...] [options]
941
1037
 
942
1038
  Claim one or more GitHub issues so parallel sessions/agents don't collide.
943
- The claim RECORD every machine reads is a branch on the git remote carrying the issue number
944
- (\`colab worktree new\` records it the moment it is cut as the claim ref refs/claims/<branch>,
945
- which no CI trigger watches — #325, #550). Also writes local state (fast path)
1039
+ The claim RECORD every machine reads is on the git remote: the claim lock refs/heads/claim/<N>,
1040
+ one per issue, taken by this command and by \`colab worktree new\` in one atomic create-only push
1041
+ (a [skip ci] commit, so no CI runs — #325, #550, #741), then the branch carrying the issue number,
1042
+ pushed at code-wrap. Two claimants for one issue race for the same lock; exactly one wins.
1043
+ A lock another tool took for this machine (an orchestrator spawning this session) is adopted.
1044
+ \`colab release\` and \`colab worktree rm\` release it. Also writes local state (fast path)
946
1045
  and the tracker (the copy people read):
947
1046
  gh issue edit N --add-assignee @me --add-label in-progress
948
1047
  Remote unreachable → REFUSED (fail closed). Tracker unreachable → the claim stands and its tracker
@@ -1120,6 +1219,26 @@ function cmdClaim(argv) {
1120
1219
  }
1121
1220
  }
1122
1221
 
1222
+ // #741: take the claim locks `refs/heads/claim/<N>` — one atomic create-only push, after every
1223
+ // refusal above and before anything local is written, so a lost race leaves nothing behind here.
1224
+ // The push decides the race the read above could only predict: two claimants that both read clear
1225
+ // ground meet at the compare-and-swap, and exactly one ref creation succeeds.
1226
+ const lockTake = takeClaimLocksFor(repoAbs, remoteCheck, nums, { branch, session, force: !!opts.force });
1227
+ if (!lockTake.ok) {
1228
+ const why = String(lockTake.stderr || '').split('\n').filter(Boolean).slice(-1)[0] || 'push refused';
1229
+ process.stderr.write(`✗ Refusing — could not take the claim lock${nums.length > 1 ? 's' : ''} ${nums.map((n) => git.claimLockRef(n)).join(' ')} on ${remoteCheck.remote} (${why}).\n`);
1230
+ process.stderr.write(' Most often another claimant took it a moment ago — the lock is created once, by one claimant (#741).\n');
1231
+ process.stderr.write(` Nothing was claimed. See who holds it: git ls-remote ${remoteCheck.remote} 'refs/heads/claim/*'\n`);
1232
+ return 1;
1233
+ }
1234
+ const lockFor = (num) => (lockTake.locks[num] ? { lock: lockTake.locks[num] } : {});
1235
+ for (const num of nums) {
1236
+ const l = lockTake.locks[num];
1237
+ if (!l) continue;
1238
+ if (lockTake.taken.includes(num)) print(` took claim lock ${remoteCheck.remote} ${l.ref} (#741)`);
1239
+ else if (l.adopted) print(` claim lock ${remoteCheck.remote} ${l.ref} was already taken on this machine for this work — adopted (#741)`);
1240
+ }
1241
+
1123
1242
  // #389: measured outside the lock (git, not state) — see the attach branch inside the mutation.
1124
1243
  const existingDir = wtName ? existingWorktreeFor(repoAbs, wtName, branch) : null;
1125
1244
  let attached = null;
@@ -1171,7 +1290,7 @@ function cmdClaim(argv) {
1171
1290
  const key = claimKey(repoAbs, num);
1172
1291
  const ex = st.claims[key];
1173
1292
  const sameHolder = !!ex && (ex.worktree || null) === (wtName || null);
1174
- const incoming = { issue: issueTag(num), repo: repoAbs, worktree: wtName, branch, host: HOST, machine: myMachineId(), session, sessionName, created: (ex && ex.created) || nowISO() };
1293
+ const incoming = { issue: issueTag(num), repo: repoAbs, worktree: wtName, branch, host: HOST, machine: myMachineId(), session, sessionName, created: (ex && ex.created) || nowISO(), ...lockFor(num) };
1175
1294
  // #264/#267: ONE merge rule for both a plain first claim (ex absent — merge is a no-op,
1176
1295
  // `incoming` passes through), a same-worktree re-claim/correction (sameHolder — a blank
1177
1296
  // branch/session/sessionName never overwrites a known value), and a --force takeover from a
@@ -1208,7 +1327,12 @@ function cmdClaim(argv) {
1208
1327
  pendingRetry.push(num);
1209
1328
  continue;
1210
1329
  }
1211
- if (!changed) { reclaimed.push(num); continue; }
1330
+ if (!changed) {
1331
+ // #741: the lock is bookkeeping, not an assertion a human reads — recorded silently.
1332
+ if (merged.lock && (!ex.lock || ex.lock.sha !== merged.lock.sha)) st.claims[key] = { ...ex, lock: merged.lock };
1333
+ reclaimed.push(num);
1334
+ continue;
1335
+ }
1212
1336
  st.claims[key] = merged;
1213
1337
  updated.push(num);
1214
1338
  updatedDetails.push({ num, branch: merged.branch, was: ex.branch || null });
@@ -1216,6 +1340,9 @@ function cmdClaim(argv) {
1216
1340
  return { created, reclaimed, updated, updatedDetails, upgraded, pendingRetry };
1217
1341
  });
1218
1342
  } catch (e) {
1343
+ // #741: nothing local landed, so the locks this call just pushed would stand on the remote owned
1344
+ // by nobody — take them back off before reporting.
1345
+ releaseClaimLocksOf(repoAbs, lockTake.taken.map((n) => ({ issue: issueTag(n), lock: lockTake.locks[n] })));
1219
1346
  // #285: an under-lock place-claim refusal is a genuine conflict, not an unreachable lock — say
1220
1347
  // so, and do not advise the worktree fallback the degrade path below is for.
1221
1348
  if (e && e.placeRace) { print(`✗ ${e.message}`); return placeRefusalCode(e.placeRace); }
@@ -2638,6 +2765,7 @@ function releaseFoundClaim(num, found, opts = {}) {
2638
2765
  warn(`gh not usable here (${ghUnusableWhy(repo)}) — released LOCAL-ONLY`);
2639
2766
  }
2640
2767
 
2768
+ let releasedLock = null;
2641
2769
  let remaining = null;
2642
2770
  let placeOutcome = null;
2643
2771
  state.mutate((st) => {
@@ -2650,6 +2778,7 @@ function releaseFoundClaim(num, found, opts = {}) {
2650
2778
  c.releasePending = true;
2651
2779
  c.releaseNote = `GitHub release failed (${nowISO()}) — retry with: colab release ${num}`;
2652
2780
  } else {
2781
+ if (c.lock) releasedLock = { issue: c.issue, lock: c.lock };
2653
2782
  delete st.claims[found.key];
2654
2783
  if (wtName) remaining = Object.values(st.claims).filter((cl) => cl.worktree === wtName).length;
2655
2784
  // #305: a claim with NO worktree took a checkout place-claim at `cmdClaim` (`takingPlace`),
@@ -2687,6 +2816,8 @@ function releaseFoundClaim(num, found, opts = {}) {
2687
2816
  });
2688
2817
 
2689
2818
  print(ghFailed ? `Release of #${num} recorded locally as PENDING (GitHub write failed — see above)` : `Released #${num} from ${shortRepo(repo)}`);
2819
+ // #741: the claim lock goes with the claim (kept, with the claim, when the tracker write failed).
2820
+ if (releasedLock) releaseClaimLocksOf(repo, [releasedLock]);
2690
2821
  // #305: say what happened to the checkout hold — silence here is what let the leak run unnoticed.
2691
2822
  // Nothing is printed when there was never a record to act on ('no-record'), which is the ordinary
2692
2823
  // case for every worktree claim and every `writes: isolated` repo.
@@ -6164,10 +6295,11 @@ function cmdWorktreeNew(argv) {
6164
6295
  const comps = claimIdentity.components(config);
6165
6296
 
6166
6297
  // ---- REFUSAL: don't build a worktree around issues someone else already holds ----
6298
+ let remoteCheck = null;
6167
6299
  if (issues.length) {
6168
6300
  const st0 = state.loadState();
6169
6301
  // #325: the remote first — the branch on it is the claim record every machine reads.
6170
- const remoteCheck = remoteClaimConflicts(st0, repoAbs, issues);
6302
+ remoteCheck = remoteClaimConflicts(st0, repoAbs, issues);
6171
6303
  if (remoteCheck.mode === 'unreachable') { printRemoteUnreachable(remoteCheck, 'worktree and its claims'); return 1; }
6172
6304
  if (remoteCheck.mode === 'no-remote') warn('no git remote — these claims are recorded on this machine only; no other machine can see them');
6173
6305
  const localConf = localClaimConflicts(st0, repoAbs, issues, name);
@@ -6251,38 +6383,32 @@ function cmdWorktreeNew(argv) {
6251
6383
  if (!add.ok) throw new UserError(`git worktree add failed: ${add.stderr}`);
6252
6384
  const baseSha = git.git(['rev-parse', '--short', `${remote}/${base}`], repoAbs).stdout;
6253
6385
 
6254
- // #325: push at cut. The branch on the remote IS the claim record another machine reads — before
6255
- // this the first push happened at code-wrap, hours after the claim, and triage named "an unpushed
6256
- // branch on another machine" as its own blind spot. `--force-with-lease=<ref>:` (empty expect) is
6257
- // CREATE-ONLY: two machines cutting the same name race on a real compare-and-swap, and the loser is
6258
- // rejected instead of overwriting. With issues to claim, a failed push takes nothing: the worktree
6259
- // and the zero-commit branch this invocation just made are removed again, so no half-claim exists
6260
- // anywhere. With no issues there is no claim to protect, and a failed push only warns.
6261
- //
6262
- // #550: what is pushed is the CLAIM REF `refs/claims/<branch>`, not the branch. A branch push fires
6263
- // every CI `push` trigger, and at cut the branch IS trunk's commit — so each cut re-ran a suite
6264
- // trunk had already passed (~27 % of one org's runs). A claim ref triggers nothing, and every
6265
- // claim reader (`remoteHeads`) lists it beside the branches. The branch itself is first pushed at
6266
- // code-wrap, when it has commits worth testing. The claim ref is deleted at `worktree rm`.
6267
- const pushRemote = git.claimRemote(repoAbs);
6268
- let pushed = false;
6269
- if (pushRemote) {
6270
- const claimRef = git.claimRef(branch);
6271
- const push = git.pushClaimRef(repoAbs, pushRemote, branch);
6272
- if (push.ok) {
6273
- pushed = true;
6274
- print(` pushed ${claimRef} → ${pushRemote} (the claim record other machines read; not a branch, so no CI runs — the branch is pushed at code-wrap)`);
6275
- } else {
6276
- const why = String(push.stderr || '').split('\n').filter(Boolean).slice(-1)[0] || `exit ${push.code}`;
6277
- if (issues.length) {
6278
- git.git(['worktree', 'remove', '--force', wtPath], repoAbs);
6279
- git.git(['branch', '-D', branch], repoAbs);
6280
- throw new UserError(`git push ${pushRemote} ${claimRef} failed (${why}) — claim NOT taken: the worktree and branch ` +
6281
- 'were removed again. The pushed claim ref is the record other machines read (#325, #550); fix the push ' +
6282
- `(access, network, or a claim ref of that name another machine just created — \`git ls-remote ${pushRemote} ${claimRef}\`) and re-run.`);
6283
- }
6284
- warn(`git push ${pushRemote} ${claimRef} failed (${why}) — worktree created, no claim ref on the remote`);
6285
- }
6386
+ // #325: the claim record goes to the remote at cut — before this the first push happened at
6387
+ // code-wrap, hours after the claim, and triage named "an unpushed branch on another machine" as its
6388
+ // own blind spot. #550 moved it off the branch (a branch push at cut re-ran CI on trunk's commit) to
6389
+ // `refs/claims/<branch>`; #741 moves it to THE lock, `refs/heads/claim/<N>` — one create-only ref
6390
+ // per issue in the branch namespace every forge accepts, so two claimants cutting different branch
6391
+ // names for one issue meet at the same compare-and-swap and exactly one wins. The lock commit
6392
+ // carries `[skip ci]`, so the #550 promise (a claim starts no CI run) holds. With issues to claim, a
6393
+ // lost or failed push takes nothing: the worktree and the zero-commit branch this invocation just
6394
+ // made are removed again, so no half-claim exists anywhere. With no issues there is no claim, and
6395
+ // nothing is pushed. The branch itself is first pushed at code-wrap; the locks go at `worktree rm`.
6396
+ const lockTake = takeClaimLocksFor(repoAbs, remoteCheck, issues, { branch, session, force: !!opts.force });
6397
+ if (!lockTake.ok) {
6398
+ const why = String(lockTake.stderr || '').split('\n').filter(Boolean).slice(-1)[0] || 'push refused';
6399
+ git.git(['worktree', 'remove', '--force', wtPath], repoAbs);
6400
+ git.git(['branch', '-D', branch], repoAbs);
6401
+ const refs = issues.map((n) => git.claimLockRef(n)).join(' ');
6402
+ throw new UserError(`git push ${remoteCheck.remote} ${refs} failed (${why}) — claim NOT taken: the worktree and branch ` +
6403
+ 'were removed again. The claim lock is the record other machines read (#325, #741); most often another claimant ' +
6404
+ `took it a moment ago — \`git ls-remote ${remoteCheck.remote} 'refs/heads/claim/*'\` — else fix the push (access, network) and re-run.`);
6405
+ }
6406
+ for (const num of issues) {
6407
+ const l = lockTake.locks[num];
6408
+ if (!l) continue;
6409
+ if (lockTake.taken.includes(num)) print(` took claim lock ${remoteCheck.remote} ${l.ref} (the claim record other machines read; [skip ci], so no CI runs — the branch is pushed at code-wrap)`);
6410
+ else if (l.adopted) print(` claim lock ${remoteCheck.remote} ${l.ref} was already taken on this machine for this work — adopted (#741)`);
6411
+ else print(` claim lock ${remoteCheck.remote} ${l.ref} is already this machine's — kept`);
6286
6412
  }
6287
6413
 
6288
6414
  // How far behind trunk the line is, as INFORMATION — never a threshold. A long-lived line is
@@ -6303,14 +6429,14 @@ function cmdWorktreeNew(argv) {
6303
6429
  }
6304
6430
 
6305
6431
  // 3. allocate ports + record worktree + claims (atomic)
6306
- // #325: if recording fails after the push above, take the pushed claim ref back off the remote —
6432
+ // #325: if recording fails after the push above, take the pushed claim locks back off the remote —
6307
6433
  // otherwise it would stand there as a claim record nothing on any machine owns, refusing every
6308
6434
  // later claim on these issues. (The local worktree is left as before this change.)
6309
6435
  let alloc;
6310
6436
  try {
6311
6437
  alloc = allocWorktreeRecord();
6312
6438
  } catch (e) {
6313
- if (pushed) git.deleteClaimRef(repoAbs, pushRemote, branch);
6439
+ releaseClaimLocksOf(repoAbs, lockTake.taken.map((n) => ({ issue: issueTag(n), lock: lockTake.locks[n] })));
6314
6440
  throw e;
6315
6441
  }
6316
6442
  function allocWorktreeRecord() { return state.mutate((st) => {
@@ -6349,7 +6475,7 @@ function cmdWorktreeNew(argv) {
6349
6475
  // kept OUT of the tracker writes below (assignee/label/comment are already there).
6350
6476
  if (ex && !ex.worktree && claimIdentity.isIntentSession(ex.session) && machine.isLocal(ex)) {
6351
6477
  st.claims[key] = claimIdentity.mergeClaimRecord(ex,
6352
- { issue: issueTag(num), repo: repoAbs, worktree: name, branch, host: HOST, machine: myMachineId(), session, sessionName, created: ex.created || nowISO() },
6478
+ { issue: issueTag(num), repo: repoAbs, worktree: name, branch, host: HOST, machine: myMachineId(), session, sessionName, created: ex.created || nowISO(), ...(lockTake.locks[num] ? { lock: lockTake.locks[num] } : {}) },
6353
6479
  { sameHolder: true });
6354
6480
  upgraded.push(num);
6355
6481
  continue;
@@ -6358,7 +6484,7 @@ function cmdWorktreeNew(argv) {
6358
6484
  // by this point, so `mergeClaimRecord` behaves the same as the direct-overwrite this used to
6359
6485
  // be — but routes it through the ONE #264 merge rule (tools/lib/claim-identity.js) rather than
6360
6486
  // a second, independently-drifting overwrite.
6361
- const incoming = { issue: issueTag(num), repo: repoAbs, worktree: name, branch, host: HOST, machine: myMachineId(), session, sessionName, created: (ex && ex.created) || nowISO() };
6487
+ const incoming = { issue: issueTag(num), repo: repoAbs, worktree: name, branch, host: HOST, machine: myMachineId(), session, sessionName, created: (ex && ex.created) || nowISO(), ...(lockTake.locks[num] ? { lock: lockTake.locks[num] } : {}) };
6362
6488
  if (ex) { dupes.push(num); st.claims[key] = claimIdentity.mergeClaimRecord(ex, incoming, { sameHolder: true }); continue; }
6363
6489
  st.claims[key] = incoming;
6364
6490
  claimedNums.push(num);
@@ -6530,6 +6656,7 @@ function cmdWorktreeRm(argv) {
6530
6656
  // record, deleted a few lines below by `delete st.places[place.placeKey(wt.path)]`.
6531
6657
  const claims = Object.keys(st.claims).filter((k) => st.claims[k].worktree === name);
6532
6658
  let deleted = 0;
6659
+ const releasedLocks = [];
6533
6660
  for (const k of claims) {
6534
6661
  const c = st.claims[k];
6535
6662
  if (gh && trackerFailedSet.has(normIssueNum(c.issue))) {
@@ -6538,6 +6665,7 @@ function cmdWorktreeRm(argv) {
6538
6665
  c.releaseNote = `GitHub release failed at worktree rm (${nowISO()}) — retry with: colab release ${normIssueNum(c.issue)}`;
6539
6666
  continue;
6540
6667
  }
6668
+ if (c.lock) releasedLocks.push({ issue: c.issue, lock: c.lock });
6541
6669
  delete st.claims[k];
6542
6670
  deleted++;
6543
6671
  }
@@ -6548,15 +6676,19 @@ function cmdWorktreeRm(argv) {
6548
6676
  // record surviving teardown is harmless: its liveness will read `false` (pid gone) the moment
6549
6677
  // anyone next checks it.
6550
6678
  if (st.places && wt.path) delete st.places[place.placeKey(wt.path)];
6551
- return { claims: deleted, freedPorts };
6679
+ return { claims: deleted, freedPorts, releasedLocks };
6552
6680
  });
6553
6681
 
6554
6682
  print(`✓ Removed worktree "${name}"`);
6555
6683
  if (removal.action === 'rm-rf') print(' (directory was a husk from an earlier interrupted removal — cleaned up directly)');
6556
- // #550: the claim ref `worktree new` pushed is this worktree's claim record on the remote — release
6557
- // it with the claims, or it would stand there refusing every later claim on these issue numbers from
6558
- // another machine. Best effort: an absent ref is fine (never pushed, a pre-#550 worktree, or already
6559
- // gone), a failed delete only warns with the command, and nothing above is undone for it.
6684
+ // #741: the claim locks the released claims held — each deleted only while it still points at the
6685
+ // recorded sha, so a lock someone else re-took is never removed. A claim whose tracker release
6686
+ // failed keeps its claim AND its lock (releasePending): the retry releases both.
6687
+ releaseClaimLocksOf(repoAbs, removed.releasedLocks || []);
6688
+ // #550: the legacy claim ref a pre-#741 `worktree new` pushed is this worktree's claim record on the
6689
+ // remote — release it with the claims, or it would stand there refusing every later claim on these
6690
+ // issue numbers from another machine. Best effort: an absent ref is fine (never pushed, a #741+
6691
+ // worktree, or already gone), a failed delete only warns with the command, and nothing above is undone.
6560
6692
  if (wt.branch) {
6561
6693
  let claimRemoteName = null;
6562
6694
  try { claimRemoteName = git.claimRemote(repoAbs); } catch { claimRemoteName = null; }
@@ -11588,7 +11720,13 @@ is pending, or green within ${shipBatch.LANE_GRACE_SEC / 60}m of settling (the s
11588
11720
  combined run red — is deleted and the batch you asked for is built in its place, so the survivors of a
11589
11721
  decline can batch without landing serially first (#391). A green one still unlanded past that grace lost
11590
11722
  its lander and is deleted and rebuilt the same way; a green one whose settle time cannot be read is
11591
- still waited on — only a provably abandoned batch is deleted (#659).
11723
+ still waited on — only a provably abandoned batch is deleted (#659). One whose combined run never
11724
+ started — no run ${shipBatch.LANE_GRACE_SEC / 60}m after it was built — is abandoned too; an unreadable build time waits (#742).
11725
+ The ref is the turn (#742): a build pushes it create-only, a split replaces it and a delete removes it
11726
+ only while it still holds the head this call read (--force-with-lease). Of two landers at one base
11727
+ exactly one push lands; the other prints "another lander took the turn" and exits 3 — run it again,
11728
+ it waits on the winner. The combined run is read through the forge engine (GitHub runs; on a Forgejo
11729
+ remote the commit statuses, where a re-run is not counted, so a red batch asks to be classified again).
11592
11730
  A call that goes serial on trunk CI not green gives up on its members, so it deletes every batch at
11593
11731
  trunk's tip whose members it ALL names (its run cancelled if still going) — nobody would ever land
11594
11732
  it, and it would hold this base for every later call; a batch also carrying another member stays (#656).
@@ -16009,6 +16147,15 @@ function workflowsFiringAt(repoAbs, treeish, branch) {
16009
16147
  return workflowTriggers.workflowsFiringOnBranchPush({ readFile, workflows, branch });
16010
16148
  }
16011
16149
 
16150
+ /**
16151
+ * #742: every run on batch `ref` at `sha`, WITH its attempt and updatedAt — read through the forge
16152
+ * contract's `runsAtRef` (GitHub: `gh run list --branch`; Forgejo: the commit's statuses), so the batch
16153
+ * turn reads the same facts on every engine. null = could not read, never "no runs".
16154
+ */
16155
+ function batchRunsAt(repoAbs, ref, sha) {
16156
+ return (forgeCi(repoAbs) || tracker.forRepo(repoAbs)).runsAtRef(ref, sha);
16157
+ }
16158
+
16012
16159
  /**
16013
16160
  * #373: may a green run on a `ship-batch/**` ref stand in for trunk's OWN run at the same sha? Only
16014
16161
  * on a repo that declared `ship-batch` > 1, only for a head commit a batch landed (its Ship-Batch:
@@ -16021,8 +16168,9 @@ function shipBatchTrunkSubstitute(repoAbs, trunk, sha) {
16021
16168
  if (!msg.ok) return null;
16022
16169
  const tr = shipBatch.parseMemberTrailers([msg.stdout])[0];
16023
16170
  if (!tr || !shipBatch.parseBatchRef(tr.ref)) return null;
16024
- const trunkRows = git.ghRunsForCommit(repoAbs, trunk, sha, 20);
16025
- const batchRows = git.ghRunsForRef(repoAbs, tr.ref, sha);
16171
+ const fc = forgeCi(repoAbs);
16172
+ const trunkRows = fc ? fc.ciRunsAt(sha) : git.ghRunsForCommit(repoAbs, trunk, sha, 20);
16173
+ const batchRows = batchRunsAt(repoAbs, tr.ref, sha);
16026
16174
  if (trunkRows === null || batchRows === null) return null;
16027
16175
  const covers = shipBatch.batchGreenCoversTrunk({
16028
16176
  trunkRows, batchRows,
@@ -16049,10 +16197,11 @@ function shipDryJsonReport(opts) {
16049
16197
  * lib/ship-batch.js laneHold; this only reads the remote.
16050
16198
  *
16051
16199
  * Inert (null, no git or gh call) unless project.yml declares ship-batch > 1, the merge target is
16052
- * trunk, and gh is usable. Out: null, or `{ held, ref, why, released, detail }`.
16200
+ * trunk, and gh is usable — or the remote is a forge the engine map names (#742: its runs are read
16201
+ * through the engine). Out: null, or `{ held, ref, why, released, detail }`.
16053
16202
  */
16054
16203
  function shipBatchLaneCheck(repoAbs, doc, trunk, target, gh, ciResult = null) {
16055
- if (target !== trunk || !gh || shipBatch.parseShipBatch(doc).n <= 1) return null;
16204
+ if (target !== trunk || shipBatch.parseShipBatch(doc).n <= 1 || (!gh && !forgeCi(repoAbs))) return null;
16056
16205
  // #605: a TRUNK RED: cure is never held by a batch (or a chain) — trunk is red, and the cure is the
16057
16206
  // way out; no batch can land on a red trunk anyway.
16058
16207
  if (ciResult && ciResult.cureVerdict && ciResult.cureVerdict.ok) {
@@ -16069,7 +16218,7 @@ function shipBatchLaneCheck(repoAbs, doc, trunk, target, gh, ciResult = null) {
16069
16218
  const chains = shipBatch.batchChains({ refs: refs.map((x) => ({ ref: x.parsed.ref, base7: x.parsed.base7, sha: x.sha })), trunkNow });
16070
16219
  const atTip = refs.filter((x) => chains.get(x.parsed.ref).rooted);
16071
16220
  const batches = atTip.map((x) => {
16072
- const runs = git.ghRunsForRef(repoAbs, x.parsed.ref, x.sha);
16221
+ const runs = batchRunsAt(repoAbs, x.parsed.ref, x.sha);
16073
16222
  let t = git.git(['log', '-1', '--format=%cI', x.sha], repoAbs);
16074
16223
  if (!t.ok) { git.git(['fetch', '-q', remote, `refs/heads/${x.parsed.ref}`], repoAbs); t = git.git(['log', '-1', '--format=%cI', x.sha], repoAbs); }
16075
16224
  const built = t.ok ? Date.parse(t.stdout.trim()) : NaN;
@@ -16237,18 +16386,45 @@ function cmdShipBatch(opts) {
16237
16386
  }
16238
16387
 
16239
16388
  const gh = isGhUsable(repoAbs);
16240
- if (!gh) throw new UserError(`gh not usable (${ghUnusableWhy(repoAbs)}) — a batch cannot read its combined run`);
16389
+ // #742: on a forge the engine map names, the combined run is read through its engine (runsAtRef).
16390
+ const fc = forgeCi(repoAbs);
16391
+ if (!gh && !fc) throw new UserError(`gh not usable (${ghUnusableWhy(repoAbs)}) — a batch cannot read its combined run`);
16241
16392
 
16242
16393
  // #415: every write on the resume path goes through here or shipBatchLand — under --dry, neither writes.
16243
- const deleteRef = (ref) => {
16394
+ // #742: every delete is leased on the head this call read (`sha`), so a ref another lander rebuilt in
16395
+ // between is never deleted from under it.
16396
+ const remoteRefSha = (ref) => {
16397
+ const r = git.git(['ls-remote', remote, `refs/heads/${ref}`], repoAbs);
16398
+ return r.ok ? (r.stdout.split('\t')[0] || '').trim() : null;
16399
+ };
16400
+ const deleteRef = (ref, sha) => {
16244
16401
  if (opts.dry) { print(` [dry] would delete ${remote}/${ref}`); return true; }
16245
- const d = git.git(['push', remote, '--delete', ref], repoAbs);
16246
- if (!d.ok) warn(`could not delete ${remote}/${ref}: ${git.gitFailureLine(d.stderr)} — delete it by hand`);
16402
+ const d = git.git(shipBatch.batchDeleteArgs({ remote, ref, expect: sha }), repoAbs);
16403
+ if (!d.ok) {
16404
+ const now = remoteRefSha(ref);
16405
+ warn(now !== null && now !== sha
16406
+ ? `did not delete ${remote}/${ref}: it ${now ? `moved to ${shortSha(now)}` : 'is already gone'} since this call read it at ${shortSha(sha)} — another lander's turn; left as it is (#742)`
16407
+ : `could not delete ${remote}/${ref}: ${git.gitFailureLine(d.stderr)} — delete it by hand`);
16408
+ }
16247
16409
  return d.ok;
16248
16410
  };
16411
+ // #742: a delete the next step depends on (the ref's base is then free for this call's build).
16412
+ // 'deleted' · 'moved' — another lander rewrote or removed it since it was read: the turn is not ours
16413
+ // to take on this call · 'failed' — any other refusal.
16414
+ const clearRef = (ref, sha) => {
16415
+ if (deleteRef(ref, sha)) return 'deleted';
16416
+ const now = remoteRefSha(ref);
16417
+ return now !== null && now !== sha ? 'moved' : 'failed';
16418
+ };
16419
+ const turnMoved = (ref) => {
16420
+ J.step = 'turn-lost';
16421
+ print(`⏸ ship-batch: ${ref} changed on ${remote} since this call read it — another lander took the turn at this base (#742). Nothing landed.`);
16422
+ print(' Run this command again: it reads the batch now there and waits on it, or builds once it lands or is declined.');
16423
+ return 3;
16424
+ };
16249
16425
  // A ref nothing can land any more may still have its run going: cancel it rather than let it finish.
16250
16426
  const cancelRuns = (ref, sha) => {
16251
- for (const r of (git.ghRunsForRef(repoAbs, ref, sha) || []).filter((x) => x.status !== 'completed' && x.databaseId)) {
16427
+ for (const r of (batchRunsAt(repoAbs, ref, sha) || []).filter((x) => x.status !== 'completed' && x.databaseId)) {
16252
16428
  if (opts.dry) { print(` [dry] would cancel run ${r.databaseId} on ${ref}`); continue; }
16253
16429
  const cx = git.ghRunCancel(repoAbs, r.databaseId);
16254
16430
  if (!cx.ok) warn(`could not cancel run ${r.databaseId} on ${ref} — it will finish on a ref that is gone`);
@@ -16285,7 +16461,7 @@ function cmdShipBatch(opts) {
16285
16461
  const b = rooted.find((x) => x.ref === ref);
16286
16462
  print(` ${ref} carries ${b.members.join(', ')} — every one going serial now, so nothing would ever land it; ${opts.dry ? 'would delete it [DRY RUN]' : 'deleting it'} (#656)`);
16287
16463
  cancelRuns(ref, b.sha);
16288
- deleteRef(ref);
16464
+ deleteRef(ref, b.sha);
16289
16465
  }
16290
16466
  }
16291
16467
  if (trunkCi === 'pending') {
@@ -16325,7 +16501,7 @@ function cmdShipBatch(opts) {
16325
16501
  print(` trunk moved since ${b.parsed.ref} was built (${b.parsed.base7} → ${shortSha(trunkNow)}) — nothing landed; rebuilding`);
16326
16502
  }
16327
16503
  swept.push({ ref: b.parsed.ref, members: offTrunk ? carriedBy(b.parsed.ref, trunkNow, b.sha) : [] });
16328
- deleteRef(b.parsed.ref);
16504
+ deleteRef(b.parsed.ref, b.sha);
16329
16505
  }
16330
16506
  const rooted = batchRefs.filter((x) => chains.get(x.parsed.ref).rooted);
16331
16507
  // Every member the chain up to `sha` carries (branch → the ref carrying it), read from its trailers.
@@ -16367,13 +16543,13 @@ function cmdShipBatch(opts) {
16367
16543
  print(` ${want} is gone and ${atTip.parsed.ref} at ${trunk}'s tip carries this batch — its parent landed; resuming on ${trunk}'s tip`);
16368
16544
  } else {
16369
16545
  const pc = chains.get(want);
16370
- const verdict = shipBatch.combinedVerdict(git.ghRunsForRef(repoAbs, want, p.sha), batchRead);
16546
+ const verdict = shipBatch.combinedVerdict(batchRunsAt(repoAbs, want, p.sha), batchRead);
16371
16547
  const child = rooted.find((x) => x !== p && p.sha.startsWith(x.parsed.base7)) || null;
16372
16548
  if (verdict.state === 'red') {
16373
16549
  if (child) {
16374
16550
  const carried = carriedBy(child.parsed.ref, p.sha, child.sha);
16375
16551
  print(`✗ ship-batch: ${want} is red (${verdict.why}) — it will not land at ${shortSha(p.sha)}, so ${child.parsed.ref} built on it cannot land in order. Nothing landed; ${child.parsed.ref} ${opts.dry ? 'would be deleted [DRY RUN]' : 'deleted'}. Rebuild with the same command without --onto once ${want} is settled.`);
16376
- deleteRef(child.parsed.ref);
16552
+ deleteRef(child.parsed.ref, child.sha);
16377
16553
  J.step = 'chained-decline';
16378
16554
  return serial(`its parent ${want} was declined — rebuild on ${trunk} once it is settled`, carried.length ? carried.map((m) => m.branch) : members);
16379
16555
  }
@@ -16400,8 +16576,12 @@ function cmdShipBatch(opts) {
16400
16576
  // #659: nor is a green one past the lane grace (laneHold's rule) — its lander is gone.
16401
16577
  let foreignStep = null;
16402
16578
  if (foreign.length) {
16403
- const runs = git.ghRunsForRef(repoAbs, atBase.parsed.ref, atBase.sha);
16404
- foreignStep = shipBatch.foreignBatchStep(shipBatch.combinedVerdict(runs, batchRead), { settledAtMs: shipBatch.settledAt(runs), nowMs: Date.now() });
16579
+ const runs = batchRunsAt(repoAbs, atBase.parsed.ref, atBase.sha);
16580
+ // #742: its build time ages a batch whose combined run never started (the build commits its head).
16581
+ const bt = git.git(['log', '-1', '--format=%cI', atBase.sha], repoAbs);
16582
+ const builtAtMs = bt.ok ? Date.parse(bt.stdout.trim()) : NaN;
16583
+ foreignStep = shipBatch.foreignBatchStep(shipBatch.combinedVerdict(runs, batchRead), {
16584
+ settledAtMs: shipBatch.settledAt(runs), builtAtMs: Number.isFinite(builtAtMs) ? builtAtMs : null, nowMs: Date.now() });
16405
16585
  }
16406
16586
  if (foreignStep && foreignStep.step === 'wait') {
16407
16587
  print(`⏸ ship-batch: another batch is in flight at this base — ${atBase.parsed.ref} carries ${inBatch.map((m) => m.branch).join(', ')}${foreignStep.why ? ` (${foreignStep.why})` : ''}.`);
@@ -16410,10 +16590,13 @@ function cmdShipBatch(opts) {
16410
16590
  }
16411
16591
  if (foreignStep) {
16412
16592
  const carried = inBatch.map((m) => m.branch).join(', ');
16413
- print(foreignStep.reason === 'abandoned'
16414
- ? ` ${atBase.parsed.ref} (${carried}) was abandoned — its ${foreignStep.why}; nothing landed from it. Deleting it and building the requested batch.`
16415
- : ` ${atBase.parsed.ref} (${carried}) was declined — its combined run is red (${foreignStep.why}); nothing landed from it. Deleting it and building the requested batch.`);
16416
- if (!opts.dry && !deleteRef(atBase.parsed.ref)) throw new UserError(`could not clear the ${foreignStep.reason === 'abandoned' ? 'abandoned' : 'declined'} ${atBase.parsed.ref} — delete it by hand (\`git push ${remote} --delete ${atBase.parsed.ref}\`), then run this command again`);
16593
+ print({
16594
+ abandoned: ` ${atBase.parsed.ref} (${carried}) was abandoned — its ${foreignStep.why}; nothing landed from it. Deleting it and building the requested batch.`,
16595
+ 'never-started': ` ${atBase.parsed.ref} (${carried}) was abandoned — ${foreignStep.why}; nothing landed from it. Deleting it and building the requested batch (#742).`,
16596
+ }[foreignStep.reason] || ` ${atBase.parsed.ref} (${carried}) was declined — its combined run is red (${foreignStep.why}); nothing landed from it. Deleting it and building the requested batch.`);
16597
+ const cleared = opts.dry ? 'deleted' : clearRef(atBase.parsed.ref, atBase.sha);
16598
+ if (cleared === 'moved') return turnMoved(atBase.parsed.ref);
16599
+ if (cleared !== 'deleted') throw new UserError(`could not clear the ${foreignStep.reason === 'red' ? 'declined' : 'abandoned'} ${atBase.parsed.ref} — delete it by hand (\`git push ${remote} --delete ${atBase.parsed.ref}\`), then run this command again`);
16417
16600
  }
16418
16601
  if (!foreignStep) {
16419
16602
  const heads = inBatch.map((m) => ({ ...m, now: git.branchRefs(repoAbs, m.branch, remote).remoteSha }));
@@ -16430,7 +16613,7 @@ function cmdShipBatch(opts) {
16430
16613
  }
16431
16614
  }
16432
16615
  }
16433
- let verdict = existing && existing.matches ? shipBatch.combinedVerdict(git.ghRunsForRef(repoAbs, existing.ref, existing.sha), batchRead) : null;
16616
+ let verdict = existing && existing.matches ? shipBatch.combinedVerdict(batchRunsAt(repoAbs, existing.ref, existing.sha), batchRead) : null;
16434
16617
  // #610: integration-profile: gated — a wave lands only on a green heavy run at its head too. The
16435
16618
  // heavy verdict joins the combined one (integration-profile.js waveVerdict), so a heavy red takes
16436
16619
  // the same re-run / split path a light red does, and the split walks toward the culprit.
@@ -16454,7 +16637,9 @@ function cmdShipBatch(opts) {
16454
16637
 
16455
16638
  if (step.step === 'rebuild') {
16456
16639
  print(` ${existing.ref} no longer carries the requested members at their current heads — rebuilding`);
16457
- deleteRef(existing.ref);
16640
+ const cleared = clearRef(existing.ref, existing.sha);
16641
+ if (cleared === 'moved') return turnMoved(existing.ref);
16642
+ if (cleared !== 'deleted') throw new UserError(`could not delete ${existing.ref} to rebuild it — delete it by hand (\`git push ${remote} --delete ${existing.ref}\`), then run this command again`);
16458
16643
  existing = null;
16459
16644
  step = { step: 'build' };
16460
16645
  }
@@ -16493,7 +16678,7 @@ function cmdShipBatch(opts) {
16493
16678
  }
16494
16679
  if (step.step === 'red-serial') {
16495
16680
  print(`✗ ship-batch: the combined run is red again after its one re-run (${verdict.why}) — nothing landed; ${existing.ref} ${opts.dry ? 'would be deleted [DRY RUN]' : 'deleted'}.`);
16496
- deleteRef(existing.ref);
16681
+ deleteRef(existing.ref, existing.sha);
16497
16682
  print(shipBatch.serialLine(existing.members.map((m) => m.branch)));
16498
16683
  return 4;
16499
16684
  }
@@ -16509,7 +16694,7 @@ function cmdShipBatch(opts) {
16509
16694
  return 3;
16510
16695
  }
16511
16696
  print(`✗ ship-batch: ${existing.ref} cannot land in order — ${ls.why}. Nothing landed; ${existing.ref} ${opts.dry ? 'would be deleted [DRY RUN]' : 'deleted'}. Rebuild with the same command without --onto.`);
16512
- deleteRef(existing.ref);
16697
+ deleteRef(existing.ref, existing.sha);
16513
16698
  return serial('its parent batch was discarded', existing.members.map((m) => m.branch));
16514
16699
  }
16515
16700
  if (step.step === 'land') return shipBatchLand(repoAbs, doc, trunk, remote, trunkNow, existing, verdict, opts);
@@ -16532,7 +16717,7 @@ function cmdShipBatch(opts) {
16532
16717
  ...(handoffs[b] ? { handoff: handoffs[b] } : {}) });
16533
16718
  report = rep.body;
16534
16719
  files = branchChangedFiles(repoAbs, trunkRef, refs.remoteSha);
16535
- ciClass = shipBatch.branchCiClass(git.ghRunForSha(repoAbs, b), workflowsFiringAt(repoAbs, refs.remoteSha, b).length > 0);
16720
+ ciClass = shipBatch.branchCiClass(fc ? fc.ciVerdict(refs.remoteSha, { branch: b }) : git.ghRunForSha(repoAbs, b), workflowsFiringAt(repoAbs, refs.remoteSha, b).length > 0);
16536
16721
  const el = rep.error ? { ok: false, why: rep.error }
16537
16722
  // #591: a refused hand-off is worded as the single door words it — the same reason, the same detail.
16538
16723
  : (report && report.handoff && !report.handoff.ok) ? { ok: false, why: `Refusing --handoff: ${report.handoff.detail}` }
@@ -16567,7 +16752,7 @@ function cmdShipBatch(opts) {
16567
16752
  // member is ready. Wait for a partner until the repo's window, counted from when it became ready.
16568
16753
  const lone = selected[0];
16569
16754
  const commitIso = git.git(['log', '-1', '--format=%cI', lone.sha], repoAbs);
16570
- const since = shipBatch.readySince(git.ghRunsForCommit(repoAbs, lone.branch, lone.sha), commitIso.ok ? commitIso.stdout.trim() : null);
16755
+ const since = shipBatch.readySince(fc ? fc.ciRunsAt(lone.sha) : git.ghRunsForCommit(repoAbs, lone.branch, lone.sha), commitIso.ok ? commitIso.stdout.trim() : null);
16571
16756
  const pw = shipBatch.partnerWait({ n: cfg.n, waitSec: waitCfg.sec, eligibleCount: 1, readySinceMs: since, nowMs: Date.now() });
16572
16757
  if (pw.wait) {
16573
16758
  print(`⏸ PARTNER-WAIT ${lone.branch} — the only ready member; ${waitCfg.reason}, ready since ${new Date(since).toISOString()}, ${ciWait.fmtDuration(pw.leftSec * 1000)} left. Nothing landed.`);
@@ -16687,10 +16872,17 @@ function cmdShipBatch(opts) {
16687
16872
  if (notJoining.length || dropped.length) print(` not in this batch: ${[...new Set([...notJoining, ...dropped.map((d) => d.branch)])].join(', ')}`);
16688
16873
  return 0;
16689
16874
  }
16690
- // --force only ever inside our own namespace: a rebuild on the same base replaces its own ref.
16691
- const push = git.run('git', ['push', '--force', remote, `${head}:refs/heads/${ref}`], { cwd: repoAbs });
16875
+ // #742: the push IS the turn, so it is leased: create-only when no batch is live at this base (a
16876
+ // fresh build, or one whose old ref this call just deleted), or — a split rebuilding its own ref in
16877
+ // place — only while the remote still holds the head this call read. Of two landers at one base,
16878
+ // exactly one push lands; the other reads the remote again and waits on the winner.
16879
+ const expect = existing && existing.ref === ref ? existing.sha : '';
16880
+ const push = git.run('git', shipBatch.batchPushArgs({ remote, head, ref, expect }), { cwd: repoAbs });
16692
16881
  cleanup();
16693
- if (!push.ok) throw new UserError(`could not push ${ref}: ${git.gitFailureLine(push.stderr)} — nothing landed`);
16882
+ if (!push.ok) {
16883
+ if (shipBatch.pushRefusal({ remoteSha: remoteRefSha(ref), head }) === 'turn-lost') return turnMoved(ref);
16884
+ throw new UserError(`could not push ${ref}: ${git.gitFailureLine(push.stderr)} — nothing landed`);
16885
+ }
16694
16886
  print(` pushed ${ref} = ${shortSha(base)} + ${built.length} commit(s) @ ${shortSha(head)} (${built.map((b) => b.branch).join(', ')})${parent ? ` — chained onto ${parent.ref}; it lands after it` : ''}`);
16695
16887
  if (overflow.length) print(` eligible but ${splitHalf ? 'held by the split' : 'over the cap'} (next batch): ${overflow.map((o) => o.branch).join(', ')}`);
16696
16888
  print(`⏸ BATCH-PENDING ${ref}@${shortSha(head)} — wait on the combined run (bounded, B1a), then run this command again. Nothing landed yet.`);
@@ -16786,7 +16978,7 @@ function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opt
16786
16978
  }
16787
16979
  print(' pushed.');
16788
16980
  deferredCollector = [];
16789
- if (!git.git(['push', remote, '--delete', existing.ref], repoAbs).ok) warnDeferred(`could not delete ${remote}/${existing.ref} — delete it by hand (it has landed)`);
16981
+ if (!git.git(shipBatch.batchDeleteArgs({ remote, ref: existing.ref, expect: existing.sha }), repoAbs).ok) warnDeferred(`could not delete ${remote}/${existing.ref} — delete it by hand (it has landed)`);
16790
16982
 
16791
16983
  // The post-ship hook runs ONCE, over the whole batch — it is a trunk-checkout event, not a member one.
16792
16984
  const changed = git.git(['diff', '--name-only', `${base}..${head}`], repoAbs);
@@ -7,6 +7,7 @@
7
7
  * #681 adds the release half: `colab release cut` / `release finalize` (human bar) / `promote` read CI
8
8
  * here and publish the release object here. So this module implements `tracker.FORGE_METHODS`:
9
9
  * ciVerdict — the CI verdict at a commit (below);
10
+ * runsAtRef — the rows at a batch head (#742): the same status read, ignoring the ref;
10
11
  * issueListAll — a READ of every issue (switch markers, the release hold, an existing tracking
11
12
  * record), in the GitHub adapter's shape; nothing here writes an issue;
12
13
  * releaseView / releaseCreate — the release object for a tag (`/releases`).
@@ -199,6 +200,16 @@ function create(repoAbs, eng) {
199
200
  return ng.length ? { ...summary, notGreen: ng } : summary;
200
201
  },
201
202
 
203
+ /**
204
+ * #742, tracker contract: the runs on batch `ref` at `sha`. A commit status belongs to the commit,
205
+ * so the ref is accepted and ignored (a batch head is a commit no other ref carries). No `attempt`:
206
+ * a re-run replaces the context's newest status, and nothing counts how often — the batch reads 1.
207
+ */
208
+ runsAtRef: (ref, sha) => {
209
+ const full = fullOf(sha);
210
+ return full ? rowsAt(full) : null;
211
+ },
212
+
202
213
  /** #681, not contract: the status rows at `sha` (statusRow's shape), or null when the read failed. */
203
214
  ciRunsAt: (sha) => {
204
215
  const full = fullOf(sha);
@@ -196,7 +196,9 @@ function sameClaimant(a, b, comps) {
196
196
  function mergeClaimRecord(existing, incoming, { sameHolder } = {}) {
197
197
  const merged = { ...incoming };
198
198
  if (existing && sameHolder) {
199
- for (const field of ['branch', 'session', 'sessionName']) {
199
+ // #741: `lock` — the remote claim lock this claim holds — survives a same-holder re-claim, or the
200
+ // release would no longer know which lock is its own.
201
+ for (const field of ['branch', 'session', 'sessionName', 'lock']) {
200
202
  if (!merged[field] && existing[field]) merged[field] = existing[field];
201
203
  }
202
204
  }
package/tools/lib/git.js CHANGED
@@ -313,21 +313,24 @@ function claimRemote(repo) {
313
313
  }
314
314
 
315
315
  /**
316
- * Every branch head on `remoteName` — plus every claim ref (`refs/claims/<branch>`, #550) — asked
317
- * of the remote directly (`ls-remote`, no fetch, no local cache): the claim record another machine
318
- * can read (#325). Unlike `existingBranchRef`, a failed ask is NOT "no branches": it returns
319
- * `{ ok: false, stderr }` so the caller can refuse (fail closed) instead of reading an unreachable
320
- * remote as clear ground. `{ ok: true, heads: [{ branch, sha, claimRef? }] }` otherwise, `sha` short
321
- * (7) — `parseRemoteHeads`.
316
+ * Every branch head on `remoteName` — plus every legacy claim ref (`refs/claims/<branch>`, #550) and
317
+ * every claim LOCK (`refs/heads/claim/<N>`, #741) — asked of the remote directly (`ls-remote`, no
318
+ * fetch, no local cache): the claim record another machine can read (#325). Unlike
319
+ * `existingBranchRef`, a failed ask is NOT "no branches": it returns `{ ok: false, stderr }` so the
320
+ * caller can refuse (fail closed) instead of reading an unreachable remote as clear ground.
321
+ * `{ ok: true, heads: [{ branch, sha, claimRef? }], locks: [{ issue, sha, fullSha }] }` otherwise,
322
+ * `sha` short (7) — `parseRemoteHeads` / `parseClaimLocks`. A lock is never a head.
322
323
  */
323
324
  function remoteHeads(repo, remoteName) {
324
325
  const r = git(['ls-remote', remoteName, 'refs/heads/*', `${CLAIM_REF_PREFIX}*`], repo, { timeoutMs: 60_000 });
325
326
  if (!r.ok) return { ok: false, stderr: r.stderr || (r.timedOut ? 'ls-remote timed out' : `exit ${r.code}`) };
326
- return { ok: true, heads: parseRemoteHeads(r.stdout) };
327
+ return { ok: true, heads: parseRemoteHeads(r.stdout), locks: parseClaimLocks(r.stdout) };
327
328
  }
328
329
 
329
330
  /**
330
- * #550 — where `colab worktree new` records a claim at cut: `refs/claims/<branch>`, NOT the branch.
331
+ * #550 — where `colab worktree new` recorded a claim at cut until #741: `refs/claims/<branch>`, NOT
332
+ * the branch. Since #741 nothing writes it; it is still READ as a holder (and deleted at
333
+ * `worktree rm`) until no checkout carries one. The lock that replaced it is below.
331
334
  * A push to `refs/heads/<branch>` fires every CI `push` trigger, and at cut the branch is identical
332
335
  * to trunk, so each claim re-ran the full suite on a commit trunk had already tested (measured: ~209
333
336
  * of 230 duplicate runs in one org over 3 days, one sha run 8 times). GitHub fires `push` workflows
@@ -349,6 +352,9 @@ function parseRemoteHeads(stdout) {
349
352
  for (const line of String(stdout || '').split('\n')) {
350
353
  const m = line.match(/^([0-9a-f]{7,})\s+refs\/(heads|claims)\/(.+)$/);
351
354
  if (!m) continue;
355
+ // #741: `refs/heads/claim/*` is the lock namespace, not a session's branch — `parseClaimLocks`
356
+ // reads it, and no head reader (claim conflicts, sweep, landed) ever sees it as a branch.
357
+ if (m[2] === 'heads' && m[3].startsWith(CLAIM_LOCK_BRANCH_PREFIX)) continue;
352
358
  if (m[2] === 'heads') heads.set(m[3], { branch: m[3], sha: m[1].slice(0, 7) });
353
359
  else claims.set(m[3], { branch: m[3], sha: m[1].slice(0, 7), claimRef: true });
354
360
  }
@@ -379,6 +385,164 @@ function deleteClaimRef(repo, remote, branch) {
379
385
  return { ok: r.ok, stderr: r.stderr };
380
386
  }
381
387
 
388
+ /**
389
+ * #741 — THE claim lock: one create-only ref per issue in the branch namespace,
390
+ * `refs/heads/claim/<N>`. Custom ref namespaces (`refs/claims/*`) are not safe to assume on every
391
+ * forge; the branch namespace is. Issue grain, so two claimants cutting DIFFERENT branch names for
392
+ * one issue race on the same ref and exactly one wins — `refs/claims/<branch>` was branch grain and
393
+ * let both through.
394
+ *
395
+ * The ref points at a parentless commit on the empty tree: it needs no trunk object locally (a
396
+ * `colab claim` has fetched nothing), it is a tiny push, and it changes no path, so `holders` and
397
+ * `landed` never list it. The `[skip ci]` line keeps the #550 promise — a claim starts no CI run —
398
+ * now that the ref sits where every `push: branches: ['**']` trigger looks (measured 2026-11-14: an
399
+ * orchestrator's `[skip ci]` lock commits on this namespace started no run).
400
+ *
401
+ * Only digit suffixes are locks; `claim/<anything else>` is some tool's own ref and is ignored.
402
+ */
403
+ const CLAIM_LOCK_BRANCH_PREFIX = 'claim/';
404
+ const CLAIM_LOCK_PREFIX = `refs/heads/${CLAIM_LOCK_BRANCH_PREFIX}`;
405
+ const CLAIM_LOCK_AUTHOR = { name: 'colab-claim', email: 'claim@colab.invalid' };
406
+ const CLAIM_LOCK_WRITER = 'colab';
407
+ function claimLockRef(num) { return `${CLAIM_LOCK_PREFIX}${num}`; }
408
+
409
+ /** `ls-remote` output → `[{ issue, sha, fullSha }]` for every `refs/heads/claim/<digits>`. Pure. */
410
+ function parseClaimLocks(stdout) {
411
+ const out = [];
412
+ for (const line of String(stdout || '').split('\n')) {
413
+ const m = line.match(/^([0-9a-f]{7,})\s+refs\/heads\/claim\/(\d+)$/);
414
+ if (!m) continue;
415
+ const issue = Number(m[2]);
416
+ if (Number.isInteger(issue) && issue > 0) out.push({ issue, sha: m[1].slice(0, 7), fullSha: m[1] });
417
+ }
418
+ return out;
419
+ }
420
+
421
+ /** One trailer value: a single line, trimmed. */
422
+ function trailerValue(v) { return String(v == null ? '' : v).replace(/[\r\n]+/g, ' ').trim(); }
423
+
424
+ /**
425
+ * The lock commit's message. Pure. The subject names every issue the push takes; the trailers say
426
+ * who holds them, readable from the ref alone by any machine. `Claimed-By: colab` marks a lock this
427
+ * tool wrote — the one kind whose ownership is decided by colab's own state, never by its
428
+ * `Machine:` line (see `remoteClaimConflicts`).
429
+ */
430
+ function claimLockMessage({ nums, branch = null, machine = '', machineId = '', session = '', claimedAt }) {
431
+ const lines = [`claim: ${nums.map((n) => `#${n}`).join(' ')}`, ''];
432
+ if (branch) lines.push(`Branch: ${trailerValue(branch)}`);
433
+ if (machine) lines.push(`Machine: ${trailerValue(machine)}`);
434
+ if (machineId) lines.push(`Machine-Id: ${trailerValue(machineId)}`);
435
+ if (session) lines.push(`Session: ${trailerValue(session)}`);
436
+ lines.push(`Claimed-At: ${trailerValue(claimedAt || new Date().toISOString())}`);
437
+ lines.push(`Claimed-By: ${CLAIM_LOCK_WRITER}`);
438
+ lines.push('[skip ci]');
439
+ return lines.join('\n') + '\n';
440
+ }
441
+
442
+ /**
443
+ * A lock commit's message (or a whole `git cat-file commit` body) → its trailers, lower-cased keys:
444
+ * `{ branch, machine, machineId, session, claimedAt, claimedBy, intent, claimId, author }`, and
445
+ * `colab: true` when this tool wrote it. Pure. Reads the other writer's format too (an
446
+ * orchestrator's `Machine:` / `Intent:` / `Claim-Id:`).
447
+ */
448
+ function parseClaimLockMessage(text) {
449
+ const s = String(text || '');
450
+ const out = { colab: false };
451
+ const am = s.match(/^author (.+?) <[^>]*>/m);
452
+ if (am) out.author = am[1];
453
+ const keys = { branch: 'branch', machine: 'machine', 'machine-id': 'machineId', session: 'session', 'claimed-at': 'claimedAt', 'claimed-by': 'claimedBy', intent: 'intent', 'claim-id': 'claimId' };
454
+ for (const line of s.split('\n')) {
455
+ const m = line.match(/^([A-Za-z][A-Za-z-]*):\s*(.*)$/);
456
+ if (!m) continue;
457
+ const k = keys[m[1].toLowerCase()];
458
+ if (k && out[k] === undefined) out[k] = m[2].trim();
459
+ }
460
+ out.colab = out.claimedBy === CLAIM_LOCK_WRITER;
461
+ return out;
462
+ }
463
+
464
+ /**
465
+ * Write the lock commit (not pushed): the empty tree, no parent, a fixed author so no `user.name`
466
+ * is needed, and `--no-gpg-sign` — signing a claim is #743's, and an unattended session must never
467
+ * stall on a key passphrase here. `{ ok, sha, stderr }`.
468
+ */
469
+ function makeClaimLockCommit(repo, message, at = new Date()) {
470
+ const tree = run('git', ['mktree'], { cwd: repo, input: '' });
471
+ if (!tree.ok) return { ok: false, stderr: tree.stderr || 'git mktree failed' };
472
+ const date = `${Math.floor(at.getTime() / 1000)} +0000`;
473
+ const env = {
474
+ ...process.env,
475
+ GIT_AUTHOR_NAME: CLAIM_LOCK_AUTHOR.name, GIT_AUTHOR_EMAIL: CLAIM_LOCK_AUTHOR.email, GIT_AUTHOR_DATE: date,
476
+ GIT_COMMITTER_NAME: CLAIM_LOCK_AUTHOR.name, GIT_COMMITTER_EMAIL: CLAIM_LOCK_AUTHOR.email, GIT_COMMITTER_DATE: date,
477
+ };
478
+ const c = run('git', ['commit-tree', '--no-gpg-sign', tree.stdout, '-F', '-'], { cwd: repo, input: message, env });
479
+ if (!c.ok) return { ok: false, stderr: c.stderr || 'git commit-tree failed' };
480
+ return { ok: true, sha: c.stdout };
481
+ }
482
+
483
+ /**
484
+ * Take the locks for `nums` on `remote`, pointing every one at `sha` — ONE atomic push, each ref
485
+ * create-only (`--force-with-lease=<ref>:` with an empty expect), so a branch carrying several
486
+ * issues takes all of them or none, and two claimants for one issue race on a real compare-and-swap
487
+ * whose loser is rejected. `expect` (issue → full sha) turns one ref's lease into "overwrite exactly
488
+ * this holder" — the `--force` takeover, never a blind overwrite.
489
+ *
490
+ * A remote that refuses `--atomic` gets the refs one by one; the first rejection rolls back the ones
491
+ * this call already took (lease-deleted on `sha`), so the outcome is still all or none.
492
+ * `{ ok, taken: [N], rejected: [N], atomic, stderr }`.
493
+ */
494
+ function takeClaimLocks(repo, remote, nums, sha, { expect = {} } = {}) {
495
+ if (!nums.length) return { ok: true, taken: [], rejected: [], atomic: true };
496
+ const lease = (n) => `--force-with-lease=${claimLockRef(n)}:${expect[n] || ''}`;
497
+ const spec = (n) => `${sha}:${claimLockRef(n)}`;
498
+ const r = git(['push', '--atomic', remote, ...nums.map(lease), ...nums.map(spec)], repo, { timeoutMs: 120_000 });
499
+ if (r.ok) return { ok: true, taken: [...nums], rejected: [], atomic: true };
500
+ if (!/atomic/i.test(r.stderr || '') || !/support/i.test(r.stderr || '')) {
501
+ return { ok: false, taken: [], rejected: [...nums], atomic: true, stderr: r.stderr || `exit ${r.code}` };
502
+ }
503
+ const taken = [];
504
+ for (const n of nums) {
505
+ const one = git(['push', remote, lease(n), spec(n)], repo, { timeoutMs: 120_000 });
506
+ if (one.ok) { taken.push(n); continue; }
507
+ for (const t of taken) releaseClaimLock(repo, remote, t, sha);
508
+ return { ok: false, taken: [], rejected: [n], atomic: false, stderr: one.stderr || `exit ${one.code}` };
509
+ }
510
+ return { ok: true, taken, rejected: [], atomic: false };
511
+ }
512
+
513
+ /**
514
+ * Release one lock — but only while it still points at `sha`, the lock this claim holds
515
+ * (`--force-with-lease=<ref>:<sha>`): a lock someone else has taken since is theirs and is never
516
+ * deleted from under them. `{ ok, absent? , moved?, stderr? }`; absent and moved are both success
517
+ * (there is nothing of ours left to release).
518
+ */
519
+ function releaseClaimLock(repo, remote, num, sha) {
520
+ const ref = claimLockRef(num);
521
+ const ls = git(['ls-remote', remote, ref], repo, { timeoutMs: 60_000 });
522
+ if (!ls.ok) return { ok: false, stderr: ls.stderr || `exit ${ls.code}` };
523
+ const now = (String(ls.stdout || '').split(/\s+/)[0] || '').trim();
524
+ if (!now) return { ok: true, absent: true };
525
+ if (sha && !now.startsWith(sha) && !String(sha).startsWith(now)) return { ok: true, moved: true, now: now.slice(0, 7) };
526
+ const r = git(['push', remote, `--force-with-lease=${ref}:${now}`, `:${ref}`], repo, { timeoutMs: 120_000 });
527
+ return { ok: r.ok, stderr: r.stderr };
528
+ }
529
+
530
+ /**
531
+ * Read who holds a lock: the commit at `fullSha`, fetched from `remote` when this clone lacks it.
532
+ * `{ ok, trailers }` (`parseClaimLockMessage`) or `{ ok: false, stderr }` — a failed read is the
533
+ * caller's to treat as foreign (fail closed).
534
+ */
535
+ function readClaimLock(repo, remote, num, fullSha) {
536
+ let body = fullSha ? git(['cat-file', 'commit', fullSha], repo) : { ok: false };
537
+ if (!body.ok) {
538
+ const f = git(['fetch', '--quiet', remote, claimLockRef(num)], repo, { timeoutMs: 60_000 });
539
+ if (!f.ok) return { ok: false, stderr: f.stderr || `exit ${f.code}` };
540
+ body = git(['cat-file', 'commit', fullSha || 'FETCH_HEAD'], repo);
541
+ if (!body.ok) return { ok: false, stderr: body.stderr || 'cat-file failed' };
542
+ }
543
+ return { ok: true, trailers: parseClaimLockMessage(body.stdout) };
544
+ }
545
+
382
546
  /** List worktree paths registered in a repo (porcelain). */
383
547
  function worktreeList(repo) {
384
548
  const r = git(['worktree', 'list', '--porcelain'], repo);
@@ -1694,6 +1858,8 @@ module.exports = {
1694
1858
  run, spawnErrorLine, git, repoRoot, mainRepoRoot, originUrl, remoteInfo, remoteName, remoteFor, remoteUrl, remoteProblem, _resetRemoteCache,
1695
1859
  detectTrunk, branchExists, branchRefs, existingBranchRef,
1696
1860
  claimRemote, remoteHeads, parseRemoteHeads, CLAIM_REF_PREFIX, claimRef, pushClaimRef, deleteClaimRef,
1861
+ CLAIM_LOCK_PREFIX, claimLockRef, parseClaimLocks, claimLockMessage, parseClaimLockMessage, makeClaimLockCommit,
1862
+ takeClaimLocks, releaseClaimLock, readClaimLock,
1697
1863
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1698
1864
  dirtyTracked, dirtyUntracked, dirtyAny,
1699
1865
  ghAvailable, ghState, ghInstalled, ghApiConditional, ghRunsAtShaRest, ghRunsAtShaUnfiltered, fullSha, ghIssueEdit, ghListLabels, ghOpenIssueNumbersByLabel, ghAssignedIssues,
@@ -213,6 +213,42 @@ function batchRefName(baseSha) {
213
213
  return `${REF_PREFIX}${String(baseSha || '').slice(0, 7)}`;
214
214
  }
215
215
 
216
+ /**
217
+ * #742: every write to a batch ref is LEASED on the value the caller read. The ref is the turn: two
218
+ * landers at one base used to push it with `--force`, the second silently replacing the first, and
219
+ * both then believed they held the turn. Now
220
+ * - a build pushes create-only (`expect` empty: the ref must not exist on the remote);
221
+ * - a split replaces its own ref only while the remote still holds the head it read (`expect` sha);
222
+ * - a delete removes only the head it read, so a ref another lander rebuilt in between survives.
223
+ * git checks the lease against the advertised value and the remote re-checks the old value on update,
224
+ * so of two concurrent pushes exactly one wins. A refusal is classified by re-reading the remote,
225
+ * never by git's wording (a racer seen late is `remote rejected`, not `stale info`).
226
+ */
227
+ const bareRef = (ref) => String(ref || '').replace(/^refs\/heads\//, '');
228
+ const leaseArg = (ref, expect) => `--force-with-lease=refs/heads/${bareRef(ref)}:${expect || ''}`;
229
+
230
+ /** `git push` argv putting `head` on batch `ref`, leased on `expect` ('' or null = create-only). Pure. */
231
+ function batchPushArgs({ remote, head, ref, expect = null }) {
232
+ return ['push', leaseArg(ref, expect), remote, `${head}:refs/heads/${bareRef(ref)}`];
233
+ }
234
+
235
+ /** `git push` argv deleting batch `ref` only while it still points at `expect` (a sha). Pure. */
236
+ function batchDeleteArgs({ remote, ref, expect }) {
237
+ if (!expect) throw new Error('batchDeleteArgs: a delete is leased on the sha that was read — none given');
238
+ return ['push', leaseArg(ref, expect), remote, '--delete', bareRef(ref)];
239
+ }
240
+
241
+ /**
242
+ * #742: a leased push of batch `ref` was refused. Did another lander take the turn? `remoteSha` is the
243
+ * ref on the remote re-read after the refusal ('' when absent), `head` what we pushed.
244
+ * 'turn-lost' the ref now holds someone else's head — wait for it (exit 3), never an error;
245
+ * 'refused' anything else (no access, a hook, a network failure) — today's refusal.
246
+ */
247
+ function pushRefusal({ remoteSha, head }) {
248
+ const r = String(remoteSha || '').trim();
249
+ return r && r !== String(head || '').trim() ? 'turn-lost' : 'refused';
250
+ }
251
+
216
252
  /** `ship-batch/<hex7>` (with or without `refs/heads/`) → `{ ref, base7 }`, else null. */
217
253
  function parseBatchRef(ref) {
218
254
  const m = /^(?:refs\/heads\/)?(ship-batch\/([0-9a-f]{7}))$/.exec(String(ref || ''));
@@ -516,10 +552,25 @@ function nextStep({ enabled, wired, trunkCi, eligibleCount = 0, existing = null,
516
552
  * time could not be read. That last one deliberately differs from laneHold, which releases
517
553
  * it: deleting another caller's green run is not undoable, so the batch door clears only a
518
554
  * provably abandoned ref (#391's pinned case, kept on purpose — recorded on #659).
519
- * `settledAtMs` is settledAt() of the ref's runs; `nowMs` the clock.
555
+ * #742: a batch whose combined run NEVER STARTED (no run at its head) is in flight only for the same
556
+ * grace, counted from when it was built: a workflow that should have fired and did not (a runner
557
+ * outage, a disabled workflow, a lander that died between push and run) would otherwise pause every
558
+ * batch at this base until trunk moved — laneHold already releases it on the serial doors.
559
+ * clear no run, built ≥ graceSec ago → `reason: 'never-started'`
560
+ * wait no run inside the grace, or no run and a build time that could not be read (as for green:
561
+ * only a provably abandoned ref is deleted).
562
+ * `settledAtMs` is settledAt() of the ref's runs; `builtAtMs` the batch head's commit time (the build
563
+ * commits it); `nowMs` the clock.
520
564
  */
521
- function foreignBatchStep(verdict, { settledAtMs = null, nowMs = null, graceSec = LANE_GRACE_SEC } = {}) {
565
+ function foreignBatchStep(verdict, { settledAtMs = null, builtAtMs = null, nowMs = null, graceSec = LANE_GRACE_SEC } = {}) {
522
566
  if (verdict && verdict.state === 'red') return { step: 'clear', reason: 'red', why: verdict.why };
567
+ if (verdict && verdict.state === 'none' && Number.isFinite(builtAtMs) && Number.isFinite(nowMs)) {
568
+ const mins = Math.max(0, Math.round((nowMs - builtAtMs) / 60000));
569
+ if ((nowMs - builtAtMs) >= graceSec * 1000) {
570
+ return { step: 'clear', reason: 'never-started', why: `no combined run ${mins}m after it was built (grace ${graceSec}s) — treated as abandoned` };
571
+ }
572
+ return { step: 'wait', why: `built ${mins}m ago, its combined run has not appeared yet; past ${Math.round(graceSec / 60)}m with no run it is cleared` };
573
+ }
523
574
  if (verdict && verdict.state === 'green' && Number.isFinite(settledAtMs) && Number.isFinite(nowMs)) {
524
575
  const mins = Math.max(0, Math.round((nowMs - settledAtMs) / 60000));
525
576
  if ((nowMs - settledAtMs) >= graceSec * 1000) {
@@ -767,6 +818,7 @@ module.exports = {
767
818
  parseShipBatch, parseShipBatchWait, parseShipBatchSteps, sizeTrailer, parseSizeTrailer, adaptiveSize, splitHalves, partnerWait, readySince, batchRefName, parseBatchRef, memberTrailer, parseMemberTrailers,
768
819
  droppedTrailer, parseDroppedTrailers, appendTrailers,
769
820
  branchCiClass, memberEligibility, selectMembers, wiring, combinedVerdict, nextStep, foreignBatchStep, givenUpRefs,
821
+ batchPushArgs, batchDeleteArgs, pushRefusal,
770
822
  batchGreenCoversTrunk, evidenceSuffix, serialLine, notStaged, landPushFailure,
771
823
  LANE_GRACE_SEC, laneHold, settledAt, MAX_CHAIN_DEPTH, batchChains, chainedLandStep,
772
824
  };
@@ -184,6 +184,12 @@ function create(repoAbs, given = {}) {
184
184
  return require('./git').summarizeRunsForCommit(clone(runs.filter((r) => r.headSha === sha && (!branch || r.headBranch === branch))), sha);
185
185
  },
186
186
 
187
+ // #742: the seeded runs on `ref` at `sha`, with attempt (default 1) — the GitHub adapter's row shape.
188
+ runsAtRef: (ref, sha) => {
189
+ if (offline || !sha) return null;
190
+ return clone(runs.filter((r) => r.headBranch === ref && r.headSha === sha)).map((r) => ({ attempt: 1, ...r }));
191
+ },
192
+
187
193
  releaseView: (tag) => {
188
194
  if (offline) return result(false);
189
195
  return releases.has(tag) ? result(true, { stdout: JSON.stringify({ tagName: tag }) }) : fail('release not found');
@@ -161,6 +161,10 @@ function create(repoAbs) {
161
161
  return branch ? git().ghRunForCommit(repoAbs, branch, sha, undefined, opts) : git().ghRunForCommitAnyRef(repoAbs, sha, undefined, opts);
162
162
  },
163
163
 
164
+ // #742: every run on batch `ref` at `sha`, with attempt and updatedAt — the read ship --batch made
165
+ // before the contract had it (ghRunsForRef, same argv).
166
+ runsAtRef: (ref, sha) => git().ghRunsForRef(repoAbs, ref, sha),
167
+
164
168
  // --- releases ----------------------------------------------------------------------------
165
169
  releaseView: (tag) => exec(['release', 'view', tag, '--json', 'tagName'], at),
166
170
  releaseCreate: (tag, { notesFile, final = false }) => {
@@ -17,7 +17,7 @@
17
17
  "labels": "the label names defined on the repo, in the order labelList returns them.",
18
18
  "issues": "[{number, title, body, state: OPEN|CLOSED, stateReason, labels: [name], assignees: [login], comments: [{author, body}], events: [{event: \"labeled\", label, actor}]}] — `events` is the label timeline claimHolder reads; the claimer is the actor of the LATEST labeled in-progress event.",
19
19
  "prs": "[{number, head, base, title, body, state: OPEN|CLOSED|MERGED, author}] — issues and pull requests share ONE number sequence, as on GitHub.",
20
- "runs": "[{headBranch, headSha, status, conclusion, event, workflowName, createdAt, databaseId}] — CI runs; runList returns them newest first by createdAt; ciVerdict (#678) summarizes the ones at one sha.",
20
+ "runs": "[{headBranch, headSha, status, conclusion, event, workflowName, createdAt, databaseId}] — CI runs; runList returns them newest first by createdAt; ciVerdict (#678) summarizes the ones at one sha; runsAtRef (#742) returns the ones on one ref at one sha as rows, with `attempt` and `updatedAt` when seeded.",
21
21
  "releases": "[{tag, prerelease}]"
22
22
  },
23
23
  "scenarios": [
@@ -255,6 +255,32 @@
255
255
  "steps": [
256
256
  { "call": "ciVerdict", "args": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", { "branch": "main" }], "expect": null }
257
257
  ]
258
+ },
259
+ {
260
+ "id": "runs-at-ref",
261
+ "description": "runsAtRef returns every CI run on one ref at one sha as rows (#742) — the facts ship --batch judges its combined run from, including when a finished run settled (updatedAt). A sha with no run on the ref is an empty list, never null.",
262
+ "given": {
263
+ "login": "alice",
264
+ "runs": [
265
+ {"headBranch": "ship-batch/1111111", "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "status": "completed", "conclusion": "success", "event": "push", "workflowName": "CI", "createdAt": "2026-11-01T10:00:00Z", "updatedAt": "2026-11-01T10:05:00Z", "databaseId": 201, "attempt": 1},
266
+ {"headBranch": "ship-batch/1111111", "headSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "status": "completed", "conclusion": "failure", "event": "push", "workflowName": "CI", "createdAt": "2026-11-01T11:00:00Z", "updatedAt": "2026-11-01T11:04:00Z", "databaseId": 202, "attempt": 1}
267
+ ]
268
+ },
269
+ "steps": [
270
+ { "call": "runsAtRef", "args": ["ship-batch/1111111", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],
271
+ "expect": [{"headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "status": "completed", "conclusion": "success", "updatedAt": "2026-11-01T10:05:00Z"}] },
272
+ { "call": "runsAtRef", "args": ["ship-batch/1111111", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"],
273
+ "expect": [{"headSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "status": "completed", "conclusion": "failure"}] },
274
+ { "call": "runsAtRef", "args": ["ship-batch/1111111", "cccccccccccccccccccccccccccccccccccccccc"], "expect": [] }
275
+ ]
276
+ },
277
+ {
278
+ "id": "runs-at-ref-unreadable",
279
+ "description": "A run read that cannot reach the tracker returns null — could not read, never an empty list a batch would take for a run that never started.",
280
+ "given": { "login": "alice", "offline": true },
281
+ "steps": [
282
+ { "call": "runsAtRef", "args": ["ship-batch/1111111", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"], "expect": null }
283
+ ]
258
284
  }
259
285
  ]
260
286
  }
@@ -24,6 +24,12 @@
24
24
  * tools/lib/ci-forgejo.js, Forgejo commit statuses and `/releases`. `CI_METHODS` stays the subset
25
25
  * the landing path (#678) needs. Which engine a repo gets is `engineFor` below.
26
26
  *
27
+ * Batch turn (#742): `runsAtRef(ref, sha)` — every CI run on one ref at one sha, as rows
28
+ * `{ headSha, status, conclusion, createdAt, updatedAt, databaseId, workflowName, attempt? }`, or null
29
+ * when the read failed ([] is "no run yet"). `colab ship --batch` judges its combined run from these
30
+ * (the attempt caps the one re-run; updatedAt dates a green settle). A forge whose CI is a commit
31
+ * status reads the commit and ignores the ref, and may omit `attempt` (read as 1).
32
+ *
27
33
  * Deliberately NOT in the contract yet (#501 left it so: no scenario needs them, and each would
28
34
  * pin a GitHub-only shape into a spec other trackers must satisfy): the raw CI-run lists and REST
29
35
  * probes behind `ciVerdict`, label create/delete/edit, raw `issue edit` flags and raw `api`
@@ -48,6 +54,7 @@ const METHODS = Object.freeze([
48
54
  { name: 'prEdit', kind: 'write', returns: 'result' },
49
55
  { name: 'runList', kind: 'read', returns: 'result + data: run[] | null' },
50
56
  { name: 'ciVerdict', kind: 'read', returns: 'run summary | null' },
57
+ { name: 'runsAtRef', kind: 'read', returns: 'run[] | null' },
51
58
  { name: 'releaseView', kind: 'read', returns: 'result' },
52
59
  { name: 'releaseCreate', kind: 'write', returns: 'result' },
53
60
  ].map(Object.freeze));
@@ -56,11 +63,12 @@ const METHODS = Object.freeze([
56
63
  const CI_METHODS = Object.freeze(['ciVerdict']);
57
64
 
58
65
  /**
59
- * The methods a forge engine implements (#681): landing (`CI_METHODS`) plus what a release needs —
66
+ * The methods a forge engine implements (#681): landing (`CI_METHODS`), the batch turn's run read
67
+ * (#742, `runsAtRef`), plus what a release needs —
60
68
  * the issue list READ (switch markers, the release hold, an existing tracking record) and the release
61
69
  * object. No issue write is here on purpose: #678's ruling keeps the forge's tracker the adopter's.
62
70
  */
63
- const FORGE_METHODS = Object.freeze([...CI_METHODS, 'issueListAll', 'releaseView', 'releaseCreate']);
71
+ const FORGE_METHODS = Object.freeze([...CI_METHODS, 'runsAtRef', 'issueListAll', 'releaseView', 'releaseCreate']);
64
72
 
65
73
  /**
66
74
  * Throw, naming every contract method `impl` lacks. Returns `impl` when it is complete.