@futurelastic/colab-handbook 1.21.0-rc.9 → 1.22.0-rc.2

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/audit/audit.mjs CHANGED
@@ -141,6 +141,8 @@ const migrationGrant = require("../tools/lib/migration-grant.js");
141
141
  const ciGrantLib = require("../tools/lib/ci-grant.js");
142
142
  // #407: the optional `trust-humans` list — read through the same module every grant reader uses.
143
143
  const trustHumansLib = require("../tools/lib/trust-humans.js");
144
+ // #739: `.github/factories.yml` — the trust file for several teams on one repository.
145
+ const factoriesLib = require("../tools/lib/factories.js");
144
146
  // #403: the `live-env:` key — read through the same module `colab gate-hermetic` uses.
145
147
  const hermeticLib = require("../tools/lib/hermetic.js");
146
148
  // #493: the `tree-reuse:` opt-out — read through the same module `colab ship` reads citations with.
@@ -1551,6 +1553,21 @@ function auditRepoInner(target, ctx) {
1551
1553
  if (!tr.valid) fail(tr.reason);
1552
1554
  }
1553
1555
 
1556
+ // ---- .github/factories.yml (#739) -----------------------------------------
1557
+ // The trust file several teams ("factories") share one repository through. Absent = nothing
1558
+ // (one team, no cross-factory rule). tools/lib/factories.js parseFactories is the one reading.
1559
+ // An invalid file fails: every reader then answers "nobody" (fail closed), so each cross-factory
1560
+ // rule the file was meant to turn on stops matching anyone — loud here, not at the next claim.
1561
+ {
1562
+ const text = src.readFile(factoriesLib.PATH);
1563
+ if (text === null || text === undefined) info.factories = null;
1564
+ else {
1565
+ const fr = factoriesLib.parseFactories(text);
1566
+ info.factories = fr.valid ? Object.keys(fr.doc.factories) : null;
1567
+ for (const why of fr.findings) fail(`${factoriesLib.PATH}: ${why}`);
1568
+ }
1569
+ }
1570
+
1554
1571
  // ---- live-env (#403) ------------------------------------------------------
1555
1572
  // `live-env: none` is the one declaration that skips code-wrap A3's hermetic second test run
1556
1573
  // (`colab gate-hermetic`). tools/lib/hermetic.js parseLiveEnv is the one reading. An invalid
package/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.21.0-rc.9"
36
+ "version": "1.22.0-rc.2"
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; }
@@ -31,9 +31,18 @@ const ANY_HEADING_RE = /^#{1,6}\s+\S/;
31
31
  /** A GitHub checklist line: `- [ ] …` or `- [x] …` (case-insensitive on the mark). */
32
32
  const ITEM_RE = /^-\s*\[([ xX])\]\s*(.+)$/;
33
33
 
34
- /** `Remainder: #M` — the trailer that hands unticked boxes to a follow-up issue, same shape as
35
- * the `Filed-by:` / `Group:` / `Because:` trailers this repo already writes onto issues. */
36
- const REMAINDER_RE = /^Remainder:\s*#(\d+)\b/im;
34
+ /** `Remainder: #M` — the declaration that hands unticked boxes to a follow-up issue, same shape as
35
+ * the `Filed-by:` / `Group:` / `Because:` trailers this repo already writes onto issues.
36
+ *
37
+ * Read ANYWHERE in a text, not only at the start of a line (#737): no rule says the declaration
38
+ * must start a line, and the two common forms people actually write were both missed — at the end
39
+ * of the unticked item it hands off (`- [ ] measure X … — Remainder: #M`) and inside a sentence or
40
+ * in bold (`item 4 moved to **Remainder: #M**`, `**Remainder:** #M`). Measured: a graded,
41
+ * CI-green branch sat refused for ~16 h until the same trailer was restated on its own line.
42
+ * The left edge still has to be a word boundary (`xRemainder:` does not count), and `#M` must be
43
+ * digits, so the `Remainder: #M` placeholder in prose and refusal messages never matches.
44
+ * Emphasis markers (`*`, `_`) are allowed on either side of the colon. */
45
+ const REMAINDER_RE = /(?<![A-Za-z0-9])Remainder[*_]*:[*_]*\s*#(\d+)\b/i;
37
46
 
38
47
  /**
39
48
  * The raw text of the `## Plan` section (between its heading and the next heading, or the end of
@@ -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
  }
@@ -0,0 +1,329 @@
1
+ 'use strict';
2
+ /**
3
+ * `.github/factories.yml` (#739, epic #738): the trust file that lets several independent teams
4
+ * ("factories") work on one repository with nothing shared but its forge.
5
+ *
6
+ * WHAT IT HOLDS. Who the teams are and what each may prove:
7
+ *
8
+ * version: 1
9
+ * steward: core # the factory that owns intake, trunk health and release
10
+ * forge: github.com # the repository's one home forge (a host name)
11
+ * factories:
12
+ * core: # a MAP keyed by factory id — never a list of factory objects
13
+ * tier: steward # steward · partner · outside
14
+ * machines: [box-a, box-b] # machine ids, unique across the whole file
15
+ * key: ssh-ed25519 AAAA… # ONE SSH public key: signs claim commits and verdict markers
16
+ * humans: [operator-a] # logins that count as a human for grants
17
+ * slices: [slice:core] # labels; each owned by exactly one factory
18
+ * steward-areas: [CONVENTIONS.md, .github/**] # paths whose change needs one steward verdict
19
+ *
20
+ * WHERE IT IS READ FROM is the caller's job, and the rule is the one `trust-humans:` follows: the
21
+ * TRUNK's committed copy, never the branch being judged — a branch that could edit this file could
22
+ * grant itself a factory, a machine or a key. Nothing here reads git.
23
+ *
24
+ * FAIL CLOSED. A malformed file is `valid: false` and every lookup answers "nobody": a reader that
25
+ * fell back to "no factories file" would silently drop every cross-factory rule the adopter
26
+ * declared the file to turn on.
27
+ *
28
+ * THE SIGNATURE FORMATS (mechanics: tools/docs/factories.md; why: docs/adr/739-*.md).
29
+ * claim commit an SSH-signed git commit, checked with `git verify-commit` against
30
+ * allowedSigners(doc, 'git') — the principal is the factory id.
31
+ * verdict marker `<!-- colab:verdict phase=<p> v=<v> head=<sha40> factory=<id> sig=<b64> -->`;
32
+ * `sig` is an SSH signature (namespace `colab-verdict`) over verdictPayload(),
33
+ * never over the comment body. `forge`, `repo` and `issue` in the payload come
34
+ * from the VERIFIER's own context, so a marker copied elsewhere fails.
35
+ *
36
+ * PURE: text or a parsed doc in, a verdict out. No git, no network, no ssh-keygen.
37
+ */
38
+
39
+ const yaml = require('./yaml.js');
40
+ const { LOGIN_RE } = require('./trust-humans.js');
41
+
42
+ /** Where the file lives, relative to the repository root. */
43
+ const PATH = '.github/factories.yml';
44
+ const VERSION = 1;
45
+ const TIERS = ['steward', 'partner', 'outside'];
46
+ const TOP_KEYS = ['version', 'steward', 'forge', 'factories', 'steward-areas'];
47
+ const FACTORY_KEYS = ['tier', 'machines', 'key', 'humans', 'slices'];
48
+
49
+ const FACTORY_ID_RE = /^[a-z0-9][a-z0-9-]{0,38}$/;
50
+ const MACHINE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
51
+ const FORGE_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$/;
52
+ const SLICE_RE = /^slice:[a-z0-9][a-z0-9._-]*$/;
53
+ /** One OpenSSH public key line: type, base64 blob, optional comment. */
54
+ const SSH_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) [A-Za-z0-9+/]+={0,2}( [^\s]+)?$/;
55
+
56
+ // ── the shared vocabulary (CONVENTIONS.md §5, *Factories*) ──────────────────────────────────
57
+ // Prose is the source; these are the machine copy. Not in tools/lib/codec yet — that is a closed
58
+ // public surface, and nothing writes these strings yet; the first writer (#743) moves what it writes.
59
+ const FACTORY_LABEL_PREFIX = 'factory:';
60
+ const SLICE_LABEL_PREFIX = 'slice:';
61
+ const QUEUE_READY_LABEL = 'queue:ready';
62
+ const REVIEW_LABEL_PREFIX = 'review:';
63
+ const AUDIT_STATUS_CONTEXT = 'audit';
64
+ /** `review/<check>@<factory>` — the commit-status context one factory's reviewer posts. */
65
+ function reviewStatusContext(check, factory) { return `review/${check}@${factory}`; }
66
+
67
+ // ── signatures ──────────────────────────────────────────────────────────────────────────────
68
+ const VERDICT_NAMESPACE = 'colab-verdict';
69
+ const CLAIM_NAMESPACE = 'git';
70
+ const PAYLOAD_HEADER = 'colab-verdict/1';
71
+ /** The signed fields, in signing order. `forge`/`repo` come from the verifier, the rest from the marker. */
72
+ const PAYLOAD_FIELDS = ['forge', 'repo', 'issue', 'phase', 'verdict', 'head', 'factory'];
73
+ const VERDICTS = ['pass', 'rework', 'blocked', 'escalate'];
74
+
75
+ function isList(v) { return Array.isArray(v); }
76
+ function str(v) { return typeof v === 'string' ? v.trim() : v; }
77
+
78
+ /**
79
+ * Two factories under one id are merged silently by the YAML subset parser (last one wins), which
80
+ * would hide exactly the clash the validator exists to report. So the raw text is read once more:
81
+ * the direct children of `factories:` and the top-level keys, each seen at most once.
82
+ */
83
+ function duplicateKeys(text) {
84
+ const out = [];
85
+ const lines = String(text).split(/\r?\n/).map((l) => l.replace(/(^|\s)#.*$/, '').replace(/\s+$/, ''))
86
+ .filter((l) => l.trim() !== '');
87
+ const top = new Map();
88
+ let inFactories = false;
89
+ let childIndent = null;
90
+ const children = new Map();
91
+ for (const l of lines) {
92
+ const indent = l.match(/^ */)[0].length;
93
+ const m = l.trim().match(/^([^:\s][^:]*):/);
94
+ if (indent === 0) {
95
+ inFactories = false;
96
+ if (m) {
97
+ top.set(m[1], (top.get(m[1]) || 0) + 1);
98
+ if (m[1] === 'factories') { inFactories = true; childIndent = null; }
99
+ }
100
+ continue;
101
+ }
102
+ if (!inFactories || !m) continue;
103
+ if (childIndent === null) childIndent = indent;
104
+ if (indent === childIndent) children.set(m[1], (children.get(m[1]) || 0) + 1);
105
+ }
106
+ for (const [k, n] of top) if (n > 1) out.push(`top-level key \`${k}\` appears ${n} times`);
107
+ for (const [k, n] of children) if (n > 1) out.push(`factory \`${k}\` is declared ${n} times — one id, one factory`);
108
+ return out;
109
+ }
110
+
111
+ /** A list field → its trimmed strings, or a finding. `allowEmpty` for `humans`. */
112
+ function listOf(v, what, re, allowEmpty, findings) {
113
+ if (v === null || v === undefined) {
114
+ if (allowEmpty) return [];
115
+ findings.push(`${what} is missing`);
116
+ return [];
117
+ }
118
+ if (!isList(v)) { findings.push(`${what} must be a list, got ${JSON.stringify(v)}`); return []; }
119
+ if (!allowEmpty && v.length === 0) { findings.push(`${what} is an empty list`); return []; }
120
+ const out = [];
121
+ for (const raw of v) {
122
+ const s = str(raw);
123
+ if (typeof s !== 'string' || !re.test(s)) findings.push(`${what} has an invalid entry ${JSON.stringify(raw)}`);
124
+ else out.push(s);
125
+ }
126
+ return out;
127
+ }
128
+
129
+ /**
130
+ * The file's text → `{ valid, findings, doc }`.
131
+ * doc — `{ version, steward, forge, factories: { <id>: { tier, machines, key, humans, slices } },
132
+ * stewardAreas }`, normalised; present even when invalid, for a reader that wants to
133
+ * print what it saw. Never act on it when `valid` is false.
134
+ * Every finding names the field and, for a clash, both factories.
135
+ */
136
+ function parseFactories(text) {
137
+ const findings = [];
138
+ let raw;
139
+ try { raw = yaml.parse(String(text == null ? '' : text)); } catch (e) {
140
+ return { valid: false, findings: [`${PATH} could not be parsed: ${e.message}`], doc: null };
141
+ }
142
+ findings.push(...duplicateKeys(text));
143
+ if (!raw || typeof raw !== 'object' || isList(raw)) {
144
+ return { valid: false, findings: [`${PATH} must be a map of keys`], doc: null };
145
+ }
146
+ for (const k of Object.keys(raw)) if (!TOP_KEYS.includes(k)) findings.push(`unknown key \`${k}\``);
147
+
148
+ if (raw.version !== VERSION) findings.push(`version must be ${VERSION}, got ${JSON.stringify(raw.version ?? null)}`);
149
+ const forge = str(raw.forge);
150
+ if (typeof forge !== 'string' || !FORGE_RE.test(forge)) findings.push(`forge must be a host name (e.g. github.com), got ${JSON.stringify(raw.forge ?? null)}`);
151
+
152
+ const factories = {};
153
+ const fs = raw.factories;
154
+ if (!fs || typeof fs !== 'object' || isList(fs)) {
155
+ findings.push('factories must be a map keyed by factory id (not a list of factory objects)');
156
+ } else {
157
+ for (const [id, f] of Object.entries(fs)) {
158
+ const where = `factories.${id}`;
159
+ if (!FACTORY_ID_RE.test(id)) findings.push(`${where}: a factory id is lowercase letters, digits and hyphens`);
160
+ if (!f || typeof f !== 'object' || isList(f)) { findings.push(`${where} must be a map`); continue; }
161
+ for (const k of Object.keys(f)) if (!FACTORY_KEYS.includes(k)) findings.push(`${where}: unknown key \`${k}\``);
162
+ const tier = str(f.tier);
163
+ if (!TIERS.includes(tier)) findings.push(`${where}.tier must be one of ${TIERS.join(' · ')}, got ${JSON.stringify(f.tier ?? null)}`);
164
+ const key = str(f.key);
165
+ if (typeof key !== 'string' || !SSH_KEY_RE.test(key)) findings.push(`${where}.key must be one SSH public key line (type, base64, optional comment)`);
166
+ factories[id] = {
167
+ tier: TIERS.includes(tier) ? tier : null,
168
+ machines: listOf(f.machines, `${where}.machines`, MACHINE_ID_RE, false, findings),
169
+ key: typeof key === 'string' && SSH_KEY_RE.test(key) ? key : null,
170
+ humans: listOf(f.humans, `${where}.humans`, LOGIN_RE, true, findings).map((h) => h.toLowerCase()),
171
+ slices: listOf(f.slices, `${where}.slices`, SLICE_RE, true, findings),
172
+ };
173
+ }
174
+ if (Object.keys(factories).length === 0) findings.push('factories declares no factory');
175
+ }
176
+
177
+ // Across the file: a machine and a slice each belong to exactly one factory.
178
+ for (const [field, noun] of [['machines', 'machine'], ['slices', 'slice']]) {
179
+ const owner = new Map();
180
+ for (const [id, f] of Object.entries(factories)) {
181
+ for (const v of f[field]) {
182
+ const prev = owner.get(v);
183
+ if (prev && prev !== id) findings.push(`${noun} \`${v}\` is claimed by both \`${prev}\` and \`${id}\` — each ${noun} belongs to one factory`);
184
+ else if (prev === id) findings.push(`${noun} \`${v}\` is listed twice in \`${id}\``);
185
+ else owner.set(v, id);
186
+ }
187
+ }
188
+ }
189
+ const keyOwner = new Map();
190
+ for (const [id, f] of Object.entries(factories)) {
191
+ if (!f.key) continue;
192
+ const blob = f.key.split(' ')[1];
193
+ if (keyOwner.has(blob)) findings.push(`factories \`${keyOwner.get(blob)}\` and \`${id}\` share one key — a key identifies one factory`);
194
+ else keyOwner.set(blob, id);
195
+ }
196
+
197
+ const steward = str(raw.steward);
198
+ const stewards = Object.entries(factories).filter(([, f]) => f.tier === 'steward').map(([id]) => id);
199
+ if (typeof steward !== 'string' || !factories[steward]) findings.push(`steward must name a declared factory, got ${JSON.stringify(raw.steward ?? null)}`);
200
+ else if (factories[steward].tier !== 'steward') findings.push(`steward \`${steward}\` must have tier steward`);
201
+ if (stewards.length > 1) findings.push(`exactly one factory has tier steward, found ${stewards.map((s) => `\`${s}\``).join(', ')}`);
202
+
203
+ const stewardAreas = listOf(raw['steward-areas'], 'steward-areas', /^\S+$/, true, findings);
204
+
205
+ const doc = { version: raw.version, steward: steward || null, forge: forge || null, factories, stewardAreas };
206
+ return { valid: findings.length === 0, findings, doc };
207
+ }
208
+
209
+ /** A parsed result, or null — the guard every lookup shares: invalid answers nobody. */
210
+ function usable(parsed) { return parsed && parsed.valid && parsed.doc ? parsed.doc : null; }
211
+
212
+ /** The factory a machine id belongs to, or null (unknown machine, or an invalid file). */
213
+ function factoryOfMachine(parsed, machine) {
214
+ const doc = usable(parsed);
215
+ if (!doc) return null;
216
+ for (const [id, f] of Object.entries(doc.factories)) if (f.machines.includes(machine)) return id;
217
+ return null;
218
+ }
219
+
220
+ /** The factory owning a slice label (`slice:<name>`), or null. */
221
+ function factoryOfSlice(parsed, label) {
222
+ const doc = usable(parsed);
223
+ if (!doc) return null;
224
+ for (const [id, f] of Object.entries(doc.factories)) if (f.slices.includes(label)) return id;
225
+ return null;
226
+ }
227
+
228
+ /** Whether `login` counts as a human of `factory` (case-insensitive, as logins are). */
229
+ function isHumanOf(parsed, factory, login) {
230
+ const doc = usable(parsed);
231
+ const f = doc && doc.factories[factory];
232
+ return !!(f && login && f.humans.includes(String(login).toLowerCase()));
233
+ }
234
+
235
+ /**
236
+ * An OpenSSH allowed_signers file for one namespace: one line per factory, principal = factory id.
237
+ * Feed it to `ssh-keygen -Y verify -f` (verdicts, namespace `colab-verdict`) or set it as
238
+ * `gpg.ssh.allowedSignersFile` for `git verify-commit` (claim commits, namespace `git`).
239
+ * An invalid file yields an EMPTY list — nothing verifies, which is the fail-closed answer.
240
+ */
241
+ function allowedSigners(parsed, namespace) {
242
+ const doc = usable(parsed);
243
+ if (!doc) return '';
244
+ return Object.entries(doc.factories)
245
+ .map(([id, f]) => `${id} namespaces="${namespace}" ${f.key.split(' ').slice(0, 2).join(' ')}\n`)
246
+ .join('');
247
+ }
248
+
249
+ const FIELD_VALUE_RE = /^[^\s=]+$/;
250
+
251
+ /**
252
+ * The canonical payload a verdict signature covers — the exact bytes, as a string:
253
+ *
254
+ * colab-verdict/1\n
255
+ * forge=<forge>\n repo=<owner/name>\n issue=<N>\n phase=<phase>\n verdict=<v>\n head=<sha40>\n factory=<id>\n
256
+ *
257
+ * (one field per line, no spaces, LF endings, a trailing LF). `ctx` = `{ forge, repo }` from the
258
+ * verifier's own context — the factories file's `forge` and the repository it is reading — never
259
+ * from the comment. `fields` = `{ issue, phase, verdict, head, factory }`: `issue` is the issue the
260
+ * comment sits on (the verifier's context again — the marker does not carry it), the rest from the
261
+ * marker.
262
+ * Throws on a field that cannot be encoded unambiguously; a signer and a verifier that disagree
263
+ * about bytes would make every signature fail, so there is no lenient mode.
264
+ */
265
+ function verdictPayload(fields, ctx) {
266
+ const all = { forge: ctx && ctx.forge, repo: ctx && ctx.repo, ...(fields || {}) };
267
+ all.issue = all.issue == null ? all.issue : String(all.issue);
268
+ if (!/^[1-9][0-9]*$/.test(all.issue || '')) throw new TypeError(`verdictPayload: issue must be a positive integer, got ${JSON.stringify(all.issue)}`);
269
+ if (!/^[0-9a-f]{40}$/.test(all.head || '')) throw new TypeError(`verdictPayload: head must be a full 40-hex commit sha, got ${JSON.stringify(all.head)}`);
270
+ if (!VERDICTS.includes(all.verdict)) throw new TypeError(`verdictPayload: verdict must be one of ${VERDICTS.join(', ')}, got ${JSON.stringify(all.verdict)}`);
271
+ if (!FACTORY_ID_RE.test(all.factory || '')) throw new TypeError(`verdictPayload: factory ${JSON.stringify(all.factory)} is not a factory id`);
272
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(all.repo || '')) throw new TypeError(`verdictPayload: repo must be owner/name, got ${JSON.stringify(all.repo)}`);
273
+ for (const k of PAYLOAD_FIELDS) {
274
+ if (typeof all[k] !== 'string' || !FIELD_VALUE_RE.test(all[k])) throw new TypeError(`verdictPayload: ${k} must be a non-empty value with no space or "=", got ${JSON.stringify(all[k])}`);
275
+ }
276
+ return `${PAYLOAD_HEADER}\n${PAYLOAD_FIELDS.map((k) => `${k}=${all[k]}`).join('\n')}\n`;
277
+ }
278
+
279
+ /** An armored SSH signature (`-----BEGIN SSH SIGNATURE-----` …) → the one-line `sig=` value. */
280
+ function sigFromArmor(armored) {
281
+ const body = String(armored || '').split(/\r?\n/).filter((l) => l && !/^-----(BEGIN|END) SSH SIGNATURE-----$/.test(l)).join('');
282
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) throw new TypeError('sigFromArmor: not an armored SSH signature');
283
+ return body;
284
+ }
285
+
286
+ /** The one-line `sig=` value → the armored form `ssh-keygen -Y verify -s` reads (70-column lines). */
287
+ function armorFromSig(sig) {
288
+ const s = String(sig || '');
289
+ const lines = s.match(/.{1,70}/g) || [];
290
+ return `-----BEGIN SSH SIGNATURE-----\n${lines.join('\n')}\n-----END SSH SIGNATURE-----\n`;
291
+ }
292
+
293
+ const MARKER_RE = /^<!-- colab:verdict ((?:[a-z][a-z0-9_-]*=[^\s=]+=* ?)+)-->$/;
294
+
295
+ /** `{ phase, verdict, head, factory, sig, extra? }` → the marker. `extra` fields ride UNSIGNED. */
296
+ function encodeVerdictMarker({ phase, verdict, head, factory, sig, extra = {} }) {
297
+ const parts = [`phase=${phase}`, `v=${verdict}`, `head=${head}`, `factory=${factory}`];
298
+ for (const [k, v] of Object.entries(extra)) parts.push(`${k}=${v}`);
299
+ parts.push(`sig=${sig}`);
300
+ for (const p of parts) if (!/^[a-z][a-z0-9_-]*=[^\s=]+=*$/.test(p)) throw new TypeError(`encodeVerdictMarker: field ${JSON.stringify(p)} cannot be encoded`);
301
+ return `<!-- colab:verdict ${parts.join(' ')} -->`;
302
+ }
303
+
304
+ /**
305
+ * One marker line → `{ phase, verdict, head, factory, sig, signed, extra }`, or null.
306
+ * `signed` is true only when it carries both `factory` and `sig` — an unsigned marker (the form
307
+ * written before #739) still decodes, and must never be read as any factory's word.
308
+ */
309
+ function decodeVerdictMarker(line) {
310
+ const m = MARKER_RE.exec(String(line || '').trim());
311
+ if (!m) return null;
312
+ const f = {};
313
+ for (const tok of m[1].trim().split(' ')) {
314
+ const i = tok.indexOf('=');
315
+ f[tok.slice(0, i)] = tok.slice(i + 1);
316
+ }
317
+ const known = new Set(['phase', 'v', 'head', 'factory', 'sig']);
318
+ const extra = Object.fromEntries(Object.entries(f).filter(([k]) => !known.has(k)));
319
+ return { phase: f.phase || null, verdict: f.v || null, head: f.head || null, factory: f.factory || null,
320
+ sig: f.sig || null, signed: !!(f.factory && f.sig), extra };
321
+ }
322
+
323
+ module.exports = {
324
+ PATH, VERSION, TIERS, VERDICTS,
325
+ FACTORY_LABEL_PREFIX, SLICE_LABEL_PREFIX, QUEUE_READY_LABEL, REVIEW_LABEL_PREFIX, AUDIT_STATUS_CONTEXT,
326
+ VERDICT_NAMESPACE, CLAIM_NAMESPACE, PAYLOAD_HEADER, PAYLOAD_FIELDS,
327
+ reviewStatusContext, parseFactories, factoryOfMachine, factoryOfSlice, isHumanOf, allowedSigners,
328
+ verdictPayload, sigFromArmor, armorFromSig, encodeVerdictMarker, decodeVerdictMarker,
329
+ };
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,