@futurelastic/colab-handbook 1.22.0-rc.4 → 1.22.0-rc.6

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.4"
36
+ "version": "1.22.0-rc.6"
37
37
  }
package/tools/colab CHANGED
@@ -64,7 +64,10 @@ const axisAuthority = require('./lib/axis-authority');
64
64
  const writesAuthority = require('./lib/writes-authority');
65
65
  const claimIdentity = require('./lib/claim-identity');
66
66
  const claimComments = require('./lib/claim-comments');
67
+ const factoriesLib = require('./lib/factories'); // #739
68
+ const claimTakeover = require('./lib/claim-takeover'); // #744
67
69
  const codec = require('./lib/codec');
70
+ const factories = require('./lib/factories');
68
71
  const machine = require('./lib/machine');
69
72
  const targetSync = require('./lib/ship-target-sync');
70
73
  const shipBatch = require('./lib/ship-batch');
@@ -340,6 +343,58 @@ function commentHost(repoAbs) {
340
343
  * `ioreg` spawn only for commands that actually write or compare a claim. */
341
344
  function myMachineId() { return machine.localMachine().id || null; }
342
345
 
346
+ /**
347
+ * #743 — this machine's FACTORY in `repoAbs`, from `.github/factories.yml` (#739) as committed on
348
+ * TRUNK — never the checkout's working tree or the branch being worked on, so no branch can name its
349
+ * own machine into a factory (CONVENTIONS §5, *Factories*). The machine is looked up by its LABEL
350
+ * (`branchName.machineLabel(HOST)` — `Box_A.local` → `box-a`), the same name the claim lock's
351
+ * `Machine:` trailer and a `branchPrefix: machine` branch carry.
352
+ *
353
+ * Returns `{ id, reason }`: `id` '' when there is no file (one team, nothing to name), the file is
354
+ * invalid (fail closed — it names nobody), or it does not list this machine. Read once per repo per
355
+ * process: one `git show`, and the answer cannot change under a running command.
356
+ */
357
+ const _factoryCache = new Map();
358
+ function factoryFor(repoAbs) {
359
+ if (_factoryCache.has(repoAbs)) return _factoryCache.get(repoAbs);
360
+ const label = branchName.machineLabel(HOST);
361
+ let out = { id: '', reason: 'no-file', machine: label };
362
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
363
+ if (trunk) {
364
+ let remote = null;
365
+ try { remote = git.remoteFor(repoAbs); } catch (_) { remote = null; }
366
+ const refs = [trunk, ...(remote ? [`${remote}/${trunk}`] : [])];
367
+ let text = null;
368
+ for (const ref of refs) {
369
+ const r = git.git(['show', `${ref}:${factories.PATH}`], repoAbs);
370
+ if (r.ok) { text = r.stdout; out.ref = ref; break; }
371
+ }
372
+ if (text !== null) {
373
+ const parsed = factories.parseFactories(text);
374
+ const id = parsed.valid ? factories.factoryOfMachine(parsed, label) : null;
375
+ out = id ? { ...out, id, reason: 'listed' }
376
+ : { ...out, reason: parsed.valid ? 'unlisted' : 'invalid', findings: parsed.findings || [] };
377
+ }
378
+ }
379
+ _factoryCache.set(repoAbs, out);
380
+ return out;
381
+ }
382
+
383
+ /** #743 — the factory id a claim/hand-off written from here names, or ''. Warns once when trunk HAS a
384
+ * factories file that names nobody for this machine — a claim then names no factory, and a reader
385
+ * degrades to comparing it by login and machine alone. */
386
+ const _factoryWarned = new Set();
387
+ function myFactory(repoAbs) {
388
+ const f = factoryFor(repoAbs);
389
+ if ((f.reason === 'unlisted' || f.reason === 'invalid') && !_factoryWarned.has(repoAbs)) {
390
+ _factoryWarned.add(repoAbs);
391
+ warn(f.reason === 'invalid'
392
+ ? `${factories.PATH} on ${f.ref} is invalid (${(f.findings || [])[0] || 'see colab audit'}) — it names no factory, so this claim names none (#743)`
393
+ : `${factories.PATH} on ${f.ref} lists no factory for machine "${f.machine}" — this claim names no factory (#743)`);
394
+ }
395
+ return f.id;
396
+ }
397
+
343
398
  /**
344
399
  * Resolve the session id for this invocation: --session flag > COLAB_SESSION env >
345
400
  * a DERIVED person identity (#528) > '' (absent, never an error). Free-form — any stable id for
@@ -545,12 +600,13 @@ function wtStatus(wt) { return (wt && wt.status) || 'running'; }
545
600
  * supplies what the codec deliberately does not hold — the clock and the machine digest. `-` stands
546
601
  * for "no branch"/"no worktree" (#53, it used to be the word `trunk`). `host` is the raw hostname
547
602
  * where the destination may name it, the `h:` token where it may not (#369, `commentHost`); the
548
- * comparable identity is the machine digest beside it (#327), omitted when no id resolved.
603
+ * comparable identity is the machine digest beside it (#327), omitted when no id resolved. `factory`
604
+ * (#743) is this machine's factory from trunk's `.github/factories.yml`, omitted when none is named.
549
605
  */
550
- function claimCommentBody(wtName, branch, session, sessionName, host = HOST) {
606
+ function claimCommentBody(wtName, branch, session, sessionName, host = HOST, factory = '') {
551
607
  return codec.encodeClaim({
552
608
  worktree: wtName, branch, host, at: nowISO(),
553
- machine: machine.machineToken(myMachineId()) || '', session, sessionName,
609
+ machine: machine.machineToken(myMachineId()) || '', factory, session, sessionName,
554
610
  });
555
611
  }
556
612
 
@@ -682,23 +738,64 @@ function takeClaimLocksFor(repoAbs, check, nums, { branch = null, session = '',
682
738
  * a failure warns with the command and undoes nothing. An adopted lock (an orchestrator's) is
683
739
  * released too — release is unconditional (CONVENTIONS.md §5), and a lock left behind would refuse
684
740
  * every other machine on that issue.
741
+ *
742
+ * #746 — a record with NO `lock` field is not skipped: its issue's lock is looked up on the remote and
743
+ * released, leased on the sha just read, when `claimIdentity.lockReleasableBy` proves it is this
744
+ * claim's; otherwise it is left and the exact delete command is printed. Such a record is written
745
+ * when the lock came from somewhere else: an orchestrator takes the lock at spawn and the session's
746
+ * claim is then recorded by a colab older than #741 (the served CLI lagging trunk — measured on #746
747
+ * itself), or `doctor --sync` re-creates the record from the tracker. Callers pass every released
748
+ * record — `{ issue, lock?, session?, branch? }` — not only the ones with a lock.
685
749
  */
686
750
  function releaseClaimLocksOf(repoAbs, claims) {
687
- const held = (claims || []).filter((c) => c && c.lock && c.lock.sha);
688
- if (!held.length) return;
751
+ const list = (claims || []).filter((c) => c && c.issue);
752
+ if (!list.length) return;
689
753
  let remote = null;
690
754
  try { remote = git.claimRemote(repoAbs); } catch { remote = null; }
691
755
  if (!remote) return;
692
- for (const c of held) {
756
+ for (const c of list) {
693
757
  const num = normIssueNum(c.issue);
694
758
  const ref = git.claimLockRef(num);
695
- const r = git.releaseClaimLock(repoAbs, remote, num, c.lock.sha);
759
+ let sha = c.lock && c.lock.sha ? String(c.lock.sha) : '';
760
+ if (!sha) {
761
+ sha = locklessClaimLockSha(repoAbs, remote, num, c);
762
+ if (!sha) continue;
763
+ }
764
+ const r = git.releaseClaimLock(repoAbs, remote, num, sha);
696
765
  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}`);
766
+ else if (r.ok && !r.absent) print(` released claim lock ${remote} ${ref}${c.lock && c.lock.sha ? '' : ' (the claim record named no lock; this one names #' + num + ' and this claimer)'}`);
698
767
  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
768
  }
700
769
  }
701
770
 
771
+ /**
772
+ * #746 — the sha to lease the release on for a claim record carrying no `lock`: the lock on the remote
773
+ * for `num`, when it names that issue and this claimer. '' when there is none, or when it is not
774
+ * provably this claim's (then the delete command is printed, never run).
775
+ */
776
+ function locklessClaimLockSha(repoAbs, remote, num, rec) {
777
+ const ref = git.claimLockRef(num);
778
+ const at = git.remoteClaimLock(repoAbs, remote, num);
779
+ if (!at.ok) {
780
+ warnDeferred(`could not look up claim lock ${remote} ${ref} for #${num} (${String(at.stderr || '').split('\n')[0]}) — if it is still there and yours, delete it: git push ${remote} --delete ${ref}`);
781
+ return '';
782
+ }
783
+ if (!at.sha) return '';
784
+ const del = `git push ${remote} --force-with-lease=${ref}:${at.sha} --delete ${ref}`;
785
+ const read = git.readClaimLock(repoAbs, remote, num, at.sha);
786
+ if (!read.ok) {
787
+ warnDeferred(`claim lock ${remote} ${ref} @ ${at.sha.slice(0, 7)} could not be read (${String(read.stderr || '').split('\n')[0]}) — left in place; if it is this claim's, delete it: ${del}`);
788
+ return '';
789
+ }
790
+ const verdict = claimIdentity.lockReleasableBy(read.trailers, rec,
791
+ { num, hostLabel: HOST, machineTok: machine.machineToken(myMachineId()) || '' });
792
+ if (!verdict.ok) {
793
+ warnDeferred(`claim lock ${remote} ${ref} @ ${at.sha.slice(0, 7)} is not provably this claim's (${verdict.why}) — left in place; if it is stale, delete it: ${del}`);
794
+ return '';
795
+ }
796
+ return at.sha;
797
+ }
798
+
702
799
  /** The refusal/stale lines for a foreign lock (#741). */
703
800
  function lockHolderText(c) {
704
801
  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(' · ');
@@ -765,9 +862,9 @@ function settleTrackerPending(repoAbs, nums, missed, owner) {
765
862
  * login+host is invisible to the check above. Read the comments too and look for exactly that.
766
863
  * A read failure (null) is skipped, never treated as free.
767
864
  */
768
- function ghClaimConflicts(repoAbs, nums, myLogin, myHost, mySession, comps, myMachine = null) {
865
+ function ghClaimConflicts(repoAbs, nums, myLogin, myHost, mySession, comps, myMachine = null, myFactoryId = '') {
769
866
  comps = comps || claimIdentity.DEFAULT_COMPONENTS;
770
- const me = { login: myLogin, host: myHost, session: mySession || '', machine: myMachine || '' };
867
+ const me = { login: myLogin, host: myHost, session: mySession || '', machine: myMachine || '', factory: myFactoryId || '' };
771
868
  const out = [];
772
869
  for (const num of nums) {
773
870
  const info = git.ghIssueView(repoAbs, num, ['assignees', 'labels', 'comments']);
@@ -792,6 +889,11 @@ function ghClaimConflicts(repoAbs, nums, myLogin, myHost, mySession, comps, myMa
792
889
  // different place to hold work in, while a session knob only ever distinguished co-tenants.
793
890
  {
794
891
  const live = liveClaimComments(info.comments || [], comps);
892
+ // #743: OUR OWN login held by ANOTHER FACTORY — two teams on one forge login (#739). The
893
+ // assignee set says nothing about it, and the machine check below may not either (two teams'
894
+ // machines can share a hostname). Checked first: it is the more specific finding.
895
+ const otherFactory = live.find((c) => c.login === myLogin && !claimIdentity.sameFactory(c, me));
896
+ if (otherFactory) { out.push({ num, assignees, otherFactory }); continue; }
795
897
  const other = live.find((c) => c.login === myLogin && !claimIdentity.sameHost(c, me));
796
898
  if (other) { out.push({ num, assignees, otherMachine: other }); continue; }
797
899
  }
@@ -839,7 +941,11 @@ function printRefusal(localConf, ghConf, remoteConf = []) {
839
941
  ` #${c.num} local: worktree "${h.worktree || '-'}" · branch ${h.branch || '-'} · host ${h.host}${sess} · since ${String(h.created).slice(0, 10)}\n`);
840
942
  }
841
943
  for (const c of ghConf) {
842
- if (c.otherMachine) {
944
+ if (c.otherFactory) {
945
+ const o = c.otherFactory;
946
+ const id = displayIdentity(o.sessionName, o.session);
947
+ process.stderr.write(` #${c.num} GitHub: live claim comment by factory ${o.factory} (host ${o.host}${id ? ` · session ${id}` : ''}) — same account, another factory (#743)\n`);
948
+ } else if (c.otherMachine) {
843
949
  const o = c.otherMachine;
844
950
  const id = displayIdentity(o.sessionName, o.session);
845
951
  process.stderr.write(` #${c.num} GitHub: live claim comment from another machine (host ${o.host}${id ? ` · session ${id}` : ''}) — same account (#325)\n`);
@@ -876,7 +982,9 @@ function printTakeover(localConf, ghConf, remoteConf = []) {
876
982
  print(` --force: taking over #${c.num} from worktree "${h.worktree || '-'}" (host ${h.host}${sess}, since ${String(h.created).slice(0, 10)})`);
877
983
  }
878
984
  for (const c of ghConf) {
879
- if (c.otherMachine) {
985
+ if (c.otherFactory) {
986
+ print(` --force: taking over #${c.num} from factory ${c.otherFactory.factory}'s claim under this account (host ${c.otherFactory.host}, #743)`);
987
+ } else if (c.otherMachine) {
880
988
  print(` --force: taking over #${c.num} from this account's claim on another machine (host ${c.otherMachine.host})`);
881
989
  } else if (c.cotenant) {
882
990
  const id = displayIdentity(c.cotenant.sessionName, c.cotenant.session) || c.cotenant.identity;
@@ -889,9 +997,113 @@ function printTakeover(localConf, ghConf, remoteConf = []) {
889
997
  }
890
998
  }
891
999
 
1000
+ /**
1001
+ * #744 — `.github/factories.yml` as committed on trunk (`<remote>/<trunk>`, else local `<trunk>`),
1002
+ * fetched first so a file landed since this clone's last fetch is not missed. Never the checkout's
1003
+ * or a branch's copy: a branch that could edit the file could make itself the holder's factory.
1004
+ * `{ present, ref, parsed? }`.
1005
+ */
1006
+ function factoriesAtTrunk(repoAbs) {
1007
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
1008
+ if (!trunk) return { present: false, ref: null };
1009
+ let remote = null;
1010
+ try { remote = git.claimRemote(repoAbs); } catch (_) { remote = null; }
1011
+ if (remote) git.git(['fetch', '--quiet', '--no-tags', remote, trunk], repoAbs, { timeoutMs: 60_000 });
1012
+ for (const ref of [remote ? `${remote}/${trunk}` : null, trunk].filter(Boolean)) {
1013
+ if (!git.git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], repoAbs).ok) continue;
1014
+ const r = git.git(['show', `${ref}:${factoriesLib.PATH}`], repoAbs);
1015
+ if (!r.ok) return { present: false, ref };
1016
+ return { present: true, ref, parsed: factoriesLib.parseFactories(r.stdout) };
1017
+ }
1018
+ return { present: false, ref: null };
1019
+ }
1020
+
1021
+ /**
1022
+ * #744 — the cross-factory bar on a `--force` takeover, shared by `colab claim` and `colab worktree
1023
+ * new --issues`. Runs only once `--force` was given over a refusal. For every issue whose holder is
1024
+ * not proven to be this machine's factory (tools/lib/claim-takeover.js `isCrossFactory`), the
1025
+ * takeover needs the holder STALE (no activity for claimTakeover.STALE_DAYS days) AND a human
1026
+ * (`COLAB_HUMAN=1` with `--answered-by`). No factories file on trunk → `{ ok: true, cross: [] }`,
1027
+ * exactly the behaviour before this. Prints its own refusal; the caller only returns 1.
1028
+ */
1029
+ function crossFactoryGate(repoAbs, nums, { localConf = [], ghConf = [], remoteConf = [], answeredBy = null } = {}) {
1030
+ const file = factoriesAtTrunk(repoAbs);
1031
+ if (!file.present) return { ok: true, cross: [] };
1032
+ const mine = claimTakeover.factoryOfMachineName(file.parsed, HOST);
1033
+ const colabHuman = process.env.COLAB_HUMAN === '1';
1034
+ const nowMs = Date.now();
1035
+ const cross = [];
1036
+ const refused = [];
1037
+ for (const num of nums) {
1038
+ const holders = [
1039
+ ...remoteConf.filter((c) => c.num === num).map((c) => ({ kind: 'remote', c })),
1040
+ ...ghConf.filter((c) => c.num === num).map((c) => ({ kind: 'gh', c })),
1041
+ ];
1042
+ if (!holders.length) continue; // only this machine's own state holds it (or nothing does)
1043
+ const factoriesOf = holders.map((h) => claimTakeover.holderFactory(file.parsed, h.kind, h.c, mine));
1044
+ if (!claimTakeover.isCrossFactory(file, mine, factoriesOf)) continue;
1045
+ const times = [];
1046
+ for (const { kind, c } of holders) {
1047
+ if (kind === 'remote') {
1048
+ const ref = c.lock ? git.claimLockRef(num) : c.claimRef ? git.claimRef(c.branch) : `refs/heads/${c.branch}`;
1049
+ times.push(git.remoteRefCommitTime(repoAbs, c.remote, ref, c.fullSha || c.sha));
1050
+ } else {
1051
+ const cm = claimTakeover.holderComment(c);
1052
+ times.push(cm && cm.at ? Date.parse(cm.at) : null);
1053
+ }
1054
+ }
1055
+ const last = claimTakeover.lastActivity(times);
1056
+ const st = claimTakeover.staleness(last, nowMs);
1057
+ const holderFactory = [...new Set(factoriesOf.filter(Boolean))].join(', ') || null;
1058
+ const v = claimTakeover.takeoverVerdict({ colabHuman, answeredBy, stale: st.stale });
1059
+ const row = { num, mine, holderFactory, last, idleDays: st.idleDays, missing: v.missing, valid: !!(file.parsed && file.parsed.valid) };
1060
+ cross.push(row);
1061
+ if (!v.ok) refused.push(row);
1062
+ }
1063
+ if (refused.length) {
1064
+ process.stderr.write(`✗ Refusing --force — taking over another factory's claim (${factoriesLib.PATH} on ${file.ref}) needs both a stale holder and a human (#744):\n`);
1065
+ for (const r of refused) {
1066
+ const who = r.valid ? `factory ${r.holderFactory || '(unknown — no record ties the holder to a factory)'}` : `a holder (the factories file is INVALID, so nobody is proven your factory: ${file.parsed.findings[0]})`;
1067
+ const since = r.last ? `last activity ${new Date(r.last).toISOString().slice(0, 10)} (${r.idleDays} day${r.idleDays === 1 ? '' : 's'} ago)` : 'last activity unreadable (never treated as stale)';
1068
+ process.stderr.write(` #${r.num} held by ${who}; this machine is ${r.mine ? `factory ${r.mine}` : 'in no factory'}; ${since}\n`);
1069
+ if (r.missing.includes('stale')) process.stderr.write(` not stale: a takeover needs no activity on the claim for ${claimTakeover.STALE_DAYS} days — ask its holder to release it instead\n`);
1070
+ if (r.missing.includes('human')) process.stderr.write(' needs a human: COLAB_HUMAN=1 colab claim <N> --force --answered-by "<your name>" (no field, flag or project.yml value lowers this bar)\n');
1071
+ }
1072
+ return { ok: false, cross };
1073
+ }
1074
+ for (const r of cross) {
1075
+ print(` --force: #${r.num} is another factory's claim (${r.holderFactory || 'holder unproven'}), idle ${r.idleDays} days — taken over by ${r.mine ? `factory ${r.mine}` : 'this machine'}, answered by ${answeredBy} (COLAB_HUMAN=1, #744)`);
1076
+ }
1077
+ return { ok: true, cross };
1078
+ }
1079
+
1080
+ /**
1081
+ * #744 — after a `--force` takeover has taken the locks: remove the displaced holder's legacy claim
1082
+ * refs (`refs/claims/<branch>`, #550). The lock itself was already overwritten under a lease on the
1083
+ * holder's sha; a real branch is never deleted — it carries commits. A cross-factory takeover also
1084
+ * leaves one comment on the issue naming who answered for it. Best effort, like every other
1085
+ * release-side write: a failure warns with the command.
1086
+ */
1087
+ function afterForcedTakeover(repoAbs, remoteConf, cross, answeredBy) {
1088
+ const seen = new Set();
1089
+ for (const c of remoteConf || []) {
1090
+ if (!c.claimRef || seen.has(c.branch)) continue;
1091
+ seen.add(c.branch);
1092
+ const r = git.deleteClaimRef(repoAbs, c.remote, c.branch);
1093
+ if (r.ok && !r.absent) print(` removed the displaced holder's claim ref ${c.remote} ${git.claimRef(c.branch)} (#744)`);
1094
+ else if (!r.ok) warnDeferred(`could not remove the displaced holder's claim ref ${c.remote} ${git.claimRef(c.branch)} (${String(r.stderr || '').split('\n')[0]}) — delete it by hand: git push ${c.remote} --delete ${git.claimRef(c.branch)}`);
1095
+ }
1096
+ for (const r of cross || []) {
1097
+ const body = `⚠️ Cross-factory takeover (#744): this claim, held by ${r.holderFactory ? `factory \`${r.holderFactory}\`` : 'a holder no record ties to a factory'} ` +
1098
+ `with no activity for ${r.idleDays} days, was taken over by ${r.mine ? `factory \`${r.mine}\`` : 'a machine in no factory'} — answered by ${answeredBy} (COLAB_HUMAN=1).`;
1099
+ const c = git.ghIssueComment(repoAbs, r.num, body);
1100
+ if (!c.ok) warn(`could not post the takeover note on #${r.num} (${String(c.stderr || '').split('\n')[0] || c.code})`);
1101
+ }
1102
+ }
1103
+
892
1104
  /** Post the claim comment (best-effort: a failure warns but never fails the claim). */
893
1105
  function postClaimComment(repoAbs, num, wtName, branch, session, sessionName) {
894
- const r = git.ghIssueComment(repoAbs, num, claimCommentBody(wtName, branch, session, sessionName, commentHost(repoAbs)));
1106
+ const r = git.ghIssueComment(repoAbs, num, claimCommentBody(wtName, branch, session, sessionName, commentHost(repoAbs), myFactory(repoAbs)));
895
1107
  if (!r.ok) warn(`could not post claim comment on #${num} (${r.stderr.split('\n')[0] || r.code}) — claim stands`);
896
1108
  }
897
1109
 
@@ -1004,7 +1216,7 @@ function commentAndTieBreak(repoAbs, nums, owner) {
1004
1216
  postClaimComment(repoAbs, num, owner.wtName, owner.branch, owner.session, owner.sessionName);
1005
1217
  const info = git.ghIssueView(repoAbs, num, ['comments']);
1006
1218
  if (!info || !Array.isArray(info.comments)) continue; // can't read comments → keep the claim
1007
- const verdict = tieBreakVerdict(info.comments, owner.myLogin, HOST, owner.session, comps, myMachineId());
1219
+ const verdict = tieBreakVerdict(info.comments, owner.myLogin, HOST, owner.session, comps, myMachineId(), myFactory(repoAbs));
1008
1220
  if (verdict.lost) {
1009
1221
  yieldIssue(repoAbs, num, verdict.winner, owner.myLogin, owner.session || null);
1010
1222
  const w = verdict.winner;
@@ -1096,12 +1308,20 @@ Options:
1096
1308
  (never probed — a human lead only). Default: auto-detect (an agent session's
1097
1309
  long-lived process, verified alive + a proven ancestor; else the parent shell,
1098
1310
  exactly as before). Also settable via COLAB_PLACE_PID.
1099
- --force take over a claim held by another worktree / GitHub user (logged, never silent)
1311
+ --force take over a claim held by another worktree / GitHub user (logged, never silent).
1312
+ The displaced holder's legacy claim ref (refs/claims/<branch>) is removed; its
1313
+ lock is overwritten; a branch with commits is never deleted (#744).
1314
+ ANOTHER FACTORY's claim (.github/factories.yml on trunk — any foreign holder not
1315
+ proven to be this machine's factory, and every holder when the file is invalid)
1316
+ needs BOTH: no activity on the claim for 5 days (the newest of the commits on
1317
+ its lock, claim ref or branch and its claim comments) AND a human — COLAB_HUMAN=1
1318
+ with --answered-by. No factories file → unchanged (#744).
1319
+ --answered-by <n> with COLAB_HUMAN=1 and --force: the human who answers for a cross-factory takeover
1100
1320
  `;
1101
1321
 
1102
1322
  function cmdClaim(argv) {
1103
1323
  const opts = parseArgs(argv, {
1104
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--session': 'session', '--session-name': 'sessionName', '--pid': 'pid' },
1324
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--session': 'session', '--session-name': 'sessionName', '--pid': 'pid', '--answered-by': 'answeredBy' },
1105
1325
  flags: { '--force': 'force', '-h': 'help', '--help': 'help' },
1106
1326
  });
1107
1327
  if (opts.help || opts._.length === 0) return print(HELP_CLAIM);
@@ -1180,10 +1400,14 @@ function cmdClaim(argv) {
1180
1400
  if (remoteCheck.mode === 'no-remote') warn('no git remote — this claim is recorded on this machine only; no other machine can see it');
1181
1401
  const remoteConf = remoteCheck.conflicts;
1182
1402
  const localConf = localClaimConflicts(st0, repoAbs, nums, wtName);
1183
- const ghConf = gh ? ghClaimConflicts(repoAbs, nums, myLogin, HOST, session, comps, myMachineId()) : [];
1403
+ const ghConf = gh ? ghClaimConflicts(repoAbs, nums, myLogin, HOST, session, comps, myMachineId(), myFactory(repoAbs)) : [];
1184
1404
  if (!gh && remoteCheck.mode === 'ok') warn(`gh not usable here (${ghUnusableWhy(repoAbs)}) — refusal checked the remote and this machine; the tracker half will be PENDING`);
1405
+ let crossTakeover = [];
1185
1406
  if (remoteConf.length || localConf.length || ghConf.length) {
1186
1407
  if (!opts.force) { printRefusal(localConf, ghConf, remoteConf); return 1; }
1408
+ const gate = crossFactoryGate(repoAbs, nums, { localConf, ghConf, remoteConf, answeredBy: opts.answeredBy || null });
1409
+ if (!gate.ok) return 1;
1410
+ crossTakeover = gate.cross;
1187
1411
  printTakeover(localConf, ghConf, remoteConf);
1188
1412
  }
1189
1413
 
@@ -1238,6 +1462,7 @@ function cmdClaim(argv) {
1238
1462
  if (lockTake.taken.includes(num)) print(` took claim lock ${remoteCheck.remote} ${l.ref} (#741)`);
1239
1463
  else if (l.adopted) print(` claim lock ${remoteCheck.remote} ${l.ref} was already taken on this machine for this work — adopted (#741)`);
1240
1464
  }
1465
+ if (opts.force && (remoteConf.length || crossTakeover.length)) afterForcedTakeover(repoAbs, remoteConf, crossTakeover, opts.answeredBy || null);
1241
1466
 
1242
1467
  // #389: measured outside the lock (git, not state) — see the attach branch inside the mutation.
1243
1468
  const existingDir = wtName ? existingWorktreeFor(repoAbs, wtName, branch) : null;
@@ -2778,7 +3003,8 @@ function releaseFoundClaim(num, found, opts = {}) {
2778
3003
  c.releasePending = true;
2779
3004
  c.releaseNote = `GitHub release failed (${nowISO()}) — retry with: colab release ${num}`;
2780
3005
  } else {
2781
- if (c.lock) releasedLock = { issue: c.issue, lock: c.lock };
3006
+ // #746: released with or without a recorded lock — a lock-less record's lock is looked up.
3007
+ releasedLock = { issue: c.issue, lock: c.lock || null, session: c.session || null, branch: c.branch || null };
2782
3008
  delete st.claims[found.key];
2783
3009
  if (wtName) remaining = Object.values(st.claims).filter((cl) => cl.worktree === wtName).length;
2784
3010
  // #305: a claim with NO worktree took a checkout place-claim at `cmdClaim` (`takingPlace`),
@@ -6048,7 +6274,9 @@ dependency symlinking, dev-server restarts) live in OPTIONAL repo hooks, not her
6048
6274
  --session-name <s> short human label for tables/messages (env COLAB_SESSION_NAME)
6049
6275
  --pid <n|none> the new worktree's place-claim liveness anchor (#288) — same meaning as
6050
6276
  \`colab claim\`'s --pid; default: auto-detect (env COLAB_PLACE_PID too)
6051
- --force take over issues already claimed by another worktree / GitHub user
6277
+ --force take over issues already claimed by another worktree / GitHub user —
6278
+ another factory's claim needs a 5-day-stale holder AND COLAB_HUMAN=1 with
6279
+ --answered-by <name>, exactly as 'colab claim --force' (see colab claim -h, #744)
6052
6280
  Claimed issues are ENFORCED: if --issues names an issue already held (locally on another
6053
6281
  worktree, or on GitHub by someone else) the command REFUSES before building anything,
6054
6282
  unless --force. On success each issue gets a "🔒 Claimed" comment + the tie-break runs;
@@ -6250,7 +6478,7 @@ function uncommittedWork(wtPath) {
6250
6478
 
6251
6479
  function cmdWorktreeNew(argv) {
6252
6480
  const opts = parseArgs(argv, {
6253
- values: { '--issues': 'issues', '--ports': 'ports', '--range': 'range', '--at': 'at', '--name': 'name', '--trunk': 'trunk', '--base': 'base', '--repo': 'repo', '--session': 'session', '--session-name': 'sessionName', '--pid': 'pid' },
6481
+ values: { '--issues': 'issues', '--ports': 'ports', '--range': 'range', '--at': 'at', '--name': 'name', '--trunk': 'trunk', '--base': 'base', '--repo': 'repo', '--session': 'session', '--session-name': 'sessionName', '--pid': 'pid', '--answered-by': 'answeredBy' },
6254
6482
  aliases: { '--issue': '--issues' },
6255
6483
  flags: { '--force': 'force', '-h': 'help', '--help': 'help' },
6256
6484
  });
@@ -6296,6 +6524,7 @@ function cmdWorktreeNew(argv) {
6296
6524
 
6297
6525
  // ---- REFUSAL: don't build a worktree around issues someone else already holds ----
6298
6526
  let remoteCheck = null;
6527
+ let crossTakeover = [];
6299
6528
  if (issues.length) {
6300
6529
  const st0 = state.loadState();
6301
6530
  // #325: the remote first — the branch on it is the claim record every machine reads.
@@ -6303,10 +6532,13 @@ function cmdWorktreeNew(argv) {
6303
6532
  if (remoteCheck.mode === 'unreachable') { printRemoteUnreachable(remoteCheck, 'worktree and its claims'); return 1; }
6304
6533
  if (remoteCheck.mode === 'no-remote') warn('no git remote — these claims are recorded on this machine only; no other machine can see them');
6305
6534
  const localConf = localClaimConflicts(st0, repoAbs, issues, name);
6306
- const ghConf = gh ? ghClaimConflicts(repoAbs, issues, myLogin, HOST, session, comps, myMachineId()) : [];
6535
+ const ghConf = gh ? ghClaimConflicts(repoAbs, issues, myLogin, HOST, session, comps, myMachineId(), myFactory(repoAbs)) : [];
6307
6536
  if (!gh && remoteCheck.mode === 'ok') warn(`gh not usable here (${ghUnusableWhy(repoAbs)}) — refusal checked the remote and this machine; the tracker half will be PENDING`);
6308
6537
  if (remoteCheck.conflicts.length || localConf.length || ghConf.length) {
6309
6538
  if (!opts.force) { printRefusal(localConf, ghConf, remoteCheck.conflicts); return 1; }
6539
+ const gate = crossFactoryGate(repoAbs, issues, { localConf, ghConf, remoteConf: remoteCheck.conflicts, answeredBy: opts.answeredBy || null });
6540
+ if (!gate.ok) return 1;
6541
+ crossTakeover = gate.cross;
6310
6542
  printTakeover(localConf, ghConf, remoteCheck.conflicts);
6311
6543
  }
6312
6544
  }
@@ -6410,6 +6642,7 @@ function cmdWorktreeNew(argv) {
6410
6642
  else if (l.adopted) print(` claim lock ${remoteCheck.remote} ${l.ref} was already taken on this machine for this work — adopted (#741)`);
6411
6643
  else print(` claim lock ${remoteCheck.remote} ${l.ref} is already this machine's — kept`);
6412
6644
  }
6645
+ if (opts.force && remoteCheck && (remoteCheck.conflicts.length || crossTakeover.length)) afterForcedTakeover(repoAbs, remoteCheck.conflicts, crossTakeover, opts.answeredBy || null);
6413
6646
 
6414
6647
  // How far behind trunk the line is, as INFORMATION — never a threshold. A long-lived line is
6415
6648
  // expected to diverge; a refusal (or a warning with a number in it) would fire on every healthy
@@ -6665,7 +6898,8 @@ function cmdWorktreeRm(argv) {
6665
6898
  c.releaseNote = `GitHub release failed at worktree rm (${nowISO()}) — retry with: colab release ${normIssueNum(c.issue)}`;
6666
6899
  continue;
6667
6900
  }
6668
- if (c.lock) releasedLocks.push({ issue: c.issue, lock: c.lock });
6901
+ // #746: every released claim, not only one recording a lock — a lock-less record's lock is looked up.
6902
+ releasedLocks.push({ issue: c.issue, lock: c.lock || null, session: c.session || null, branch: c.branch || null });
6669
6903
  delete st.claims[k];
6670
6904
  deleted++;
6671
6905
  }
@@ -14793,7 +15027,8 @@ function applyShipHandoff(repoAbs, sess, opts, trunk) {
14793
15027
  sess.handoffRefs = new Set(v.refIssues || []);
14794
15028
  // #372: the implementer is the executor that handed off — name it, never leave it reading as the shipper.
14795
15029
  const claimed = v.issues.find((n) => !sess.handoffRefs.has(n));
14796
- const ex = (claimsByIssue[claimed] || []).find((c) => c.branch === sess.branch && c.login === v.executor.login);
15030
+ const ex = (claimsByIssue[claimed] || []).find((c) => c.branch === sess.branch && c.login === v.executor.login
15031
+ && shipHandoff.sameFactory(c.factory, v.executor.factory)); // #743: the same login under another factory is another holder
14797
15032
  if (ex && (ex.session || ex.sessionName)) sess.holder = { session: ex.session || '', sessionName: ex.sessionName || '' };
14798
15033
  return v;
14799
15034
  }
@@ -18075,6 +18310,44 @@ function cmdInstructionFiles(argv) {
18075
18310
  return 0;
18076
18311
  }
18077
18312
 
18313
+ const HELP_FACTORY = `colab factory [--repo <path>] [--json]
18314
+
18315
+ This machine's FACTORY in a repo (#743): the id \`.github/factories.yml\` (#739), as committed on
18316
+ TRUNK, lists this machine under — the id a 🔒 claim comment written from here carries
18317
+ (\`· factory \\\`<id>\\\`\`) and the one code-wrap's hand-off marker names (\`factory=<id>\`).
18318
+ The machine is looked up by its label (the hostname's first label, lower-cased, \`[a-z0-9-]\` only),
18319
+ the name the claim lock's \`Machine:\` trailer carries.
18320
+
18321
+ exit 0 the file lists this machine; prints the id
18322
+ exit 1 no factories file on trunk (one team — name no factory), the file is invalid
18323
+ (it names nobody), or it does not list this machine — prints why, on stderr
18324
+ --json { factory, reason: listed|no-file|invalid|unlisted, machine, ref, findings? }
18325
+ `;
18326
+
18327
+ function cmdFactory(argv) {
18328
+ const opts = parseArgs(argv, {
18329
+ values: { '--repo': 'repo' },
18330
+ flags: { '--json': 'json', '-h': 'help', '--help': 'help' },
18331
+ });
18332
+ if (opts.help) return print(HELP_FACTORY);
18333
+ const repoAbs = resolveRepo(opts);
18334
+ if (!git.repoRoot(repoAbs)) throw new UserError(`${repoAbs} is not a git repo — run it inside the repo, or pass --repo <path>`);
18335
+ const f = factoryFor(repoAbs);
18336
+ if (opts.json) {
18337
+ print(JSON.stringify({ factory: f.id || null, reason: f.reason, machine: f.machine, ref: f.ref || null,
18338
+ ...(f.findings && f.findings.length ? { findings: f.findings } : {}) }, null, 2));
18339
+ return f.id ? 0 : 1;
18340
+ }
18341
+ if (f.id) { print(f.id); return 0; }
18342
+ const why = {
18343
+ 'no-file': `no ${factories.PATH} on trunk — one team; a claim names no factory`,
18344
+ invalid: `${factories.PATH} on ${f.ref} is invalid — it names nobody (${(f.findings || [])[0] || 'see colab audit'})`,
18345
+ unlisted: `${factories.PATH} on ${f.ref} lists no factory for machine "${f.machine}"`,
18346
+ }[f.reason] || f.reason;
18347
+ process.stderr.write(`colab factory: ${why}\n`);
18348
+ return 1;
18349
+ }
18350
+
18078
18351
  function cmdHolders(argv) {
18079
18352
  const opts = parseArgs(argv, {
18080
18353
  values: { '--repo': 'repo', '--base': 'base' },
@@ -18763,6 +19036,9 @@ Commands:
18763
19036
  holders <path> [--base B] [--json] who else is holding <path> — refs that touched it and
18764
19037
  have not landed on the base (filters the raw git-log
18765
19038
  one-liner through \`landed\`'s content classification)
19039
+ factory [--json] this machine's factory in the repo, from trunk's
19040
+ .github/factories.yml (#743) — what a claim and a
19041
+ hand-off marker name
18766
19042
  instruction-files [--base B | --staged] [--json]
18767
19043
  CLAUDE.md is only @AGENTS.md + tool blocks? ratcheted:
18768
19044
  fails only where the change touches it or would regress
@@ -18859,6 +19135,7 @@ function main(argv) {
18859
19135
  case 'trunk-ci': return cmdTrunkCi(rest);
18860
19136
  case 'ci-wait': return cmdCiWait(rest);
18861
19137
  case 'holders': return cmdHolders(rest);
19138
+ case 'factory': return cmdFactory(rest);
18862
19139
  case 'instruction-files': return cmdInstructionFiles(rest);
18863
19140
  case 'promote': return cmdPromote(rest);
18864
19141
  case 'deliver': return cmdDeliver(rest);
@@ -54,7 +54,7 @@ function releaseComments(sorted) {
54
54
  }
55
55
 
56
56
  /**
57
- * Live claim comments on an issue. Returns [{login, host, machine, session, sessionName, at,
57
+ * Live claim comments on an issue. Returns [{login, host, machine, factory, session, sessionName, at,
58
58
  * branch, worktree, identity}], `at` = the comment's real GitHub createdAt (authoritative, sub-second). `identity`
59
59
  * is built from `comps` (claim-identity.js `components()`, #267); the raw fields are returned too
60
60
  * for callers that need `sameClaimant`'s degrade-on-missing comparison.
@@ -92,7 +92,8 @@ function liveClaimComments(comments, comps) {
92
92
  const machineTok = claim.machine; // #327 — '' on a legacy comment: compared by host
93
93
  const at = c.createdAt;
94
94
  // #578: branch/worktree ride along so a reader can ask WHICH branch a live claim holds.
95
- const entry = { login, host, machine: machineTok, session, sessionName, at, branch: claim.branch, worktree: claim.worktree };
95
+ // #743: the factory too — the same login under another factory is another holder (sameClaimant).
96
+ const entry = { login, host, machine: machineTok, factory: claim.factory || '', session, sessionName, at, branch: claim.branch, worktree: claim.worktree };
96
97
  const cancelled = releases.some((r) => r.at > at && (r.kind === 'release'
97
98
  || (r.login === login && !isNamedWinner(entry, r.winner))));
98
99
  if (!cancelled) live.push({ ...entry, identity: claimIdentity.identityString({ login, host, session }, comps) });
@@ -102,7 +103,7 @@ function liveClaimComments(comments, comps) {
102
103
 
103
104
  /**
104
105
  * Deterministic verdict on the simultaneous-claim race. Given the issue's comments and our own
105
- * identity (`myLogin`/`myHost`/`mySession`/`myMachine`): if a live claim that is NOT us under
106
+ * identity (`myLogin`/`myHost`/`mySession`/`myMachine`/`myFactory` — #743): if a live claim that is NOT us under
106
107
  * `comps` (`sameClaimant`, #267) is EARLIER than our own earliest live claim, by no more than
107
108
  * `RACE_WINDOW_MS` → we lost (returns the winner). Exact-timestamp ties break on identity string
108
109
  * (lexicographically smaller identity wins), so both racers, reading the same comments, reach the
@@ -122,10 +123,10 @@ function liveClaimComments(comments, comps) {
122
123
  * a record posts a SECOND comment from us, and anchoring on the latest of those would let that
123
124
  * correction restart our own priority — costing us a race we had already won.
124
125
  */
125
- function tieBreakVerdict(comments, myLogin, myHost, mySession, comps, myMachine = null) {
126
+ function tieBreakVerdict(comments, myLogin, myHost, mySession, comps, myMachine = null, myFactory = '') {
126
127
  comps = comps || claimIdentity.DEFAULT_COMPONENTS;
127
128
  const live = liveClaimComments(comments, comps);
128
- const me = { login: myLogin, host: myHost, session: mySession || '', machine: myMachine || '' };
129
+ const me = { login: myLogin, host: myHost, session: mySession || '', machine: myMachine || '', factory: myFactory || '' };
129
130
  const mine = live
130
131
  .filter((c) => claimIdentity.sameClaimant(c, me, comps))
131
132
  .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))[0]; // our EARLIEST live claim
@@ -35,6 +35,7 @@
35
35
  */
36
36
 
37
37
  const machine = require('./machine');
38
+ const { machineLabel } = require('./branch-name');
38
39
 
39
40
  const DEFAULT_COMPONENTS = Object.freeze(['login', 'host']);
40
41
  const FINE_COMPONENTS = Object.freeze(['login', 'host', 'session']);
@@ -159,9 +160,25 @@ function machineScheme(id) {
159
160
  return i === -1 ? '' : id.slice(0, i);
160
161
  }
161
162
 
163
+ /**
164
+ * Could `a` and `b` be the SAME factory (#743)? Two teams may work one repository under one forge
165
+ * login (`.github/factories.yml`, #739), so a login match alone no longer names a holder: a claim
166
+ * that names factory `x` and one that names `y` are two holders, whatever login posted them. Like
167
+ * the session (DEGRADE-ON-MISSING above), the factory decides only when BOTH sides carry one — a
168
+ * comment written before #743, or on a repository with no factories file, names none, and must not
169
+ * turn our own earlier claim into a stranger's. Not behind the claimIdentity knob: the factories
170
+ * file is itself the adopter's declaration that factories are distinct holders.
171
+ */
172
+ function sameFactory(a, b) {
173
+ const af = String((a && a.factory) || '').trim();
174
+ const bf = String((b && b.factory) || '').trim();
175
+ return !af || !bf || af === bf;
176
+ }
177
+
162
178
  /**
163
179
  * Are `a` and `b` the SAME claimant under `comps`? `login` and the machine (`sameHost`, #327) are
164
- * always required to match — they are the baseline every component set includes. `session`
180
+ * always required to match — they are the baseline every component set includes — and so is the
181
+ * factory where both name one (`sameFactory`, #743). `session`
165
182
  * sharpens the match ONLY when `comps` includes it AND both sides carry a non-empty value that is a
166
183
  * real session; either side blank, or either side a planner intent id (#326 — replaced by the real
167
184
  * session at spawn, so it is not a different claimant), degrades that pair back to the coarse
@@ -170,6 +187,7 @@ function machineScheme(id) {
170
187
  function sameClaimant(a, b, comps) {
171
188
  if (!a || !b) return false;
172
189
  if ((a.login || '') !== (b.login || '')) return false;
190
+ if (!sameFactory(a, b)) return false;
173
191
  if (!sameHost(a, b)) return false;
174
192
  if (comps && comps.includes('session') && a.session && b.session
175
193
  && !isIntentSession(a.session) && !isIntentSession(b.session)) {
@@ -222,11 +240,52 @@ function mergeClaimRecord(existing, incoming, { sameHolder } = {}) {
222
240
  * False for '' / null: absence is `warnWeakIdentity`'s and `requirePlaceIdentity`'s subject
223
241
  * (#11/#242), never this predicate's — callers test blankness first.
224
242
  */
243
+ /**
244
+ * #746 — may a claim record that carries NO `lock` field release the claim lock found on the remote
245
+ * for its issue? Pure. `trailers` is `git.parseClaimLockMessage` of the lock commit, `rec` the claim
246
+ * record being released, `here` = `{ num, hostLabel, machineTok }` (this machine's `machineLabel` and
247
+ * public machine token). `{ ok: true }` or `{ ok: false, why }` — a refusal leaves the lock in place
248
+ * and the caller prints the delete command, so this errs toward "not provably ours".
249
+ *
250
+ * A record is lock-less when the lock was written by something other than the colab that wrote the
251
+ * record: an orchestrator takes the lock at spawn and the session's claim is then recorded by a colab
252
+ * that predates #741 (measured on #746 itself — the served CLI lagged trunk), or `doctor --sync`
253
+ * re-creates the record from the tracker. So the rule mirrors adoption in `remoteClaimConflicts`:
254
+ * - the lock must name this issue in its subject (`claim: #N …`);
255
+ * - a lock colab wrote (`Claimed-By: colab`) is this claim's only when its `Session:` equals the
256
+ * record's (both non-empty) AND it names this machine — two colab homes on one host share the
257
+ * hardware, so the machine alone never proves it;
258
+ * - a lock another tool wrote is this claim's when it names this machine — the same test that let
259
+ * the session adopt it — unless a `Session:`/`Branch:` it does carry contradicts the record.
260
+ */
261
+ function lockReleasableBy(trailers, rec, { num, hostLabel = '', machineTok = '' } = {}) {
262
+ const tr = trailers || {};
263
+ const r = rec || {};
264
+ const issues = Array.isArray(tr.issues) ? tr.issues : [];
265
+ if (!issues.includes(Number(num))) {
266
+ return { ok: false, why: issues.length ? `the lock commit names ${issues.map((n) => `#${n}`).join(' ')}, not #${num}` : `the lock commit names no issue` };
267
+ }
268
+ const trMachine = tr.machine ? machineLabel(tr.machine) : '';
269
+ const onThisMachine = (tr.machineId && machineTok) ? tr.machineId === machineTok : (!!trMachine && trMachine === machineLabel(hostLabel));
270
+ if (tr.colab) {
271
+ if (!r.session || !tr.session || r.session !== tr.session) {
272
+ return { ok: false, why: `colab wrote it for session ${tr.session || '(none)'}, this claim is session ${r.session || '(none)'}` };
273
+ }
274
+ if (!onThisMachine) return { ok: false, why: `colab wrote it on machine ${tr.machine || tr.machineId || '(none)'}` };
275
+ return { ok: true };
276
+ }
277
+ const writer = tr.author || 'another tool';
278
+ if (!onThisMachine) return { ok: false, why: `${writer} wrote it for machine ${tr.machine || '(none)'}, not this one` };
279
+ if (tr.session && r.session && tr.session !== r.session) return { ok: false, why: `${writer} wrote it for session ${tr.session}, this claim is session ${r.session}` };
280
+ if (tr.branch && r.branch && tr.branch !== r.branch) return { ok: false, why: `${writer} wrote it for branch ${tr.branch}, this claim is on ${r.branch}` };
281
+ return { ok: true };
282
+ }
283
+
225
284
  const { looksLikeSessionId } = require('./codec/claim'); // one copy of the rule, in the codec (#497)
226
285
 
227
286
  module.exports = {
228
287
  DEFAULT_COMPONENTS, FINE_COMPONENTS,
229
288
  claimIdentityProblem, components, identityString, sameClaimant, mergeClaimRecord,
230
- looksLikeSessionId, isIntentSession, sameHost,
231
- shouldDerivePersonSession, derivePersonSession, isPersonSession,
289
+ looksLikeSessionId, isIntentSession, sameHost, sameFactory,
290
+ shouldDerivePersonSession, derivePersonSession, isPersonSession, lockReleasableBy,
232
291
  };
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+ /**
3
+ * #744 — `colab claim --force` over ANOTHER FACTORY's claim.
4
+ *
5
+ * Before this, `--force` took over any holder without a human; only a live checkout place-claim
6
+ * asked for `COLAB_HUMAN=1`. Inside one team that is a session clearing a dead colleague's claim.
7
+ * Across factories (`.github/factories.yml`, #739) it is one team taking another team's work, so the
8
+ * takeover needs both of:
9
+ *
10
+ * - the STALE rule — nothing new on the holder's claim for STALE_DAYS (5) days: the newest commit
11
+ * on any remote ref that carries the issue (the claim lock, a legacy claim ref, the claim's
12
+ * branch), or, with no remote ref at all, the newest live claim comment; and
13
+ * - a HUMAN — `COLAB_HUMAN=1` together with `--answered-by <name>`, the bar `colab release
14
+ * finalize` and `colab ship`'s human door already use.
15
+ *
16
+ * WHO IS ANOTHER FACTORY. Read from trunk's committed factories file only (the caller's job, the
17
+ * `trust-humans:` rule). No file → one team, the rule is off and `--force` behaves as before. A file
18
+ * is present → a foreign holder counts as another factory UNLESS it is proven to be this machine's
19
+ * own factory: an unknown holder (a branch with no machine prefix, an agent login, a machine the file
20
+ * does not list) and an invalid file both fail closed, the stance `factories.js` takes everywhere.
21
+ *
22
+ * PURE: decisions over values the caller read. No git, no network, no clock (`nowMs` is passed in).
23
+ */
24
+
25
+ const { machineLabel, parse: parseBranch } = require('./branch-name.js');
26
+ const { sameHostName } = require('./machine.js');
27
+
28
+ const STALE_DAYS = 5;
29
+ const DAY_MS = 24 * 60 * 60 * 1000;
30
+
31
+ function usableDoc(parsed) { return parsed && parsed.valid && parsed.doc ? parsed.doc : null; }
32
+
33
+ /**
34
+ * The factory a machine NAME belongs to, compared as branch-prefix labels on both sides (`Box_A.local`
35
+ * and `box-a` are one machine), or null. A factories file lists machine ids as labels, and a claim
36
+ * lock's `Machine:` trailer is one.
37
+ */
38
+ function factoryOfMachineName(parsed, name) {
39
+ const doc = usableDoc(parsed);
40
+ const want = machineLabel(name || '');
41
+ if (!doc || !want) return null;
42
+ for (const [id, f] of Object.entries(doc.factories)) {
43
+ if (f.machines.some((m) => machineLabel(m) === want)) return id;
44
+ }
45
+ return null;
46
+ }
47
+
48
+ /** The factory a hostname — raw, or the `h:` token a public claim comment carries — belongs to. */
49
+ function factoryOfHost(parsed, host) {
50
+ const doc = usableDoc(parsed);
51
+ if (!doc || !host) return null;
52
+ for (const [id, f] of Object.entries(doc.factories)) {
53
+ if (f.machines.some((m) => sameHostName(m, host))) return id;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /** The ONE factory every login in `logins` is a declared human of, or null (none, or split). */
59
+ function factoryOfLogins(parsed, logins) {
60
+ const doc = usableDoc(parsed);
61
+ if (!doc || !logins || !logins.length) return null;
62
+ const ids = new Set();
63
+ for (const login of logins) {
64
+ const l = String(login || '').toLowerCase();
65
+ const id = Object.entries(doc.factories).find(([, f]) => f.humans.includes(l));
66
+ if (!id) return null;
67
+ ids.add(id[0]);
68
+ }
69
+ return ids.size === 1 ? [...ids][0] : null;
70
+ }
71
+
72
+ /**
73
+ * The factory holding a conflict, or null when the record does not say. `c` is one entry of the
74
+ * conflict lists `colab claim` builds:
75
+ * kind 'remote' — `{ lock, machine, branch, claimRef }`: a lock names its machine; a branch (or a
76
+ * legacy claim ref) names one only through a `<login>/<machine>/` prefix.
77
+ * kind 'gh' — `{ assignees, otherFactory?, otherMachine?, cotenant? }`: a claim comment names
78
+ * its factory (#743) or, before that, its host; an assignee with no comment is
79
+ * resolved through the file's `humans`.
80
+ * kind 'local' — this machine's own state, so this machine's factory.
81
+ */
82
+ function holderFactory(parsed, kind, c, mine = null) {
83
+ if (!usableDoc(parsed) || !c) return null;
84
+ if (kind === 'local') return mine;
85
+ if (kind === 'remote') {
86
+ if (c.lock) return factoryOfMachineName(parsed, c.machine) || prefixFactory(parsed, c.branch);
87
+ return prefixFactory(parsed, c.branch);
88
+ }
89
+ if (kind === 'gh') {
90
+ const comment = holderComment(c);
91
+ // #743: a live claim comment names its factory outright; the host is the fallback for a comment
92
+ // written before #743. Never the assignee once a comment exists: on `otherFactory` the assignee
93
+ // is OUR OWN login (one login, two teams), and resolving it would name this factory — fail open.
94
+ if (comment) {
95
+ return String(comment.factory || '').trim()
96
+ || factoryOfHost(parsed, comment.host) || factoryOfLogins(parsed, [comment.login]);
97
+ }
98
+ return factoryOfLogins(parsed, c.assignees || []);
99
+ }
100
+ return null;
101
+ }
102
+
103
+ /**
104
+ * The live claim comment a `gh` conflict carries, or null: `otherFactory` (#743 — our own login under
105
+ * another factory, the more specific finding, so first), `otherMachine` (#325), `cotenant` (#327).
106
+ */
107
+ function holderComment(c) {
108
+ return (c && (c.otherFactory || c.otherMachine || c.cotenant)) || null;
109
+ }
110
+
111
+ function prefixFactory(parsed, branch) {
112
+ const p = branch ? parseBranch(branch) : null;
113
+ return p && p.machine ? factoryOfMachineName(parsed, p.machine) : null;
114
+ }
115
+
116
+ /**
117
+ * Is taking over ONE issue a cross-factory takeover? `file` = `{ present, parsed }` read from trunk;
118
+ * `holders` = the factory each record holding the issue resolves to (`holderFactory`), null where a
119
+ * record does not say. One issue is often held by several records of ONE holder — a lock naming its
120
+ * machine, an assignee naming nothing — so a silent record defers to one that speaks.
121
+ * no file → false (one team; nothing here applies)
122
+ * invalid file → true (fail closed: an invalid file trusts nobody)
123
+ * a record proves another factory → true
124
+ * no record proves any factory → true (a holder nothing ties to this team)
125
+ * every proving record says mine → false
126
+ */
127
+ function isCrossFactory(file, mine, holders) {
128
+ if (!file || !file.present) return false;
129
+ if (!usableDoc(file.parsed)) return true;
130
+ const proven = (holders || []).filter(Boolean);
131
+ if (!mine || !proven.length) return true;
132
+ return proven.some((f) => f !== mine);
133
+ }
134
+
135
+ /**
136
+ * The newest activity time (ms) across what a holder left — commit times of its remote refs and the
137
+ * times of its live claim comments — or null when nothing could be read. `times` = numbers or null.
138
+ */
139
+ function lastActivity(times) {
140
+ const known = (times || []).filter((t) => Number.isFinite(t));
141
+ return known.length ? Math.max(...known) : null;
142
+ }
143
+
144
+ /** `{ stale, idleDays }` — unknown activity is never stale (fail closed). */
145
+ function staleness(lastMs, nowMs, days = STALE_DAYS) {
146
+ if (!Number.isFinite(lastMs) || !Number.isFinite(nowMs)) return { stale: false, idleDays: null };
147
+ const idle = nowMs - lastMs;
148
+ return { stale: idle >= days * DAY_MS, idleDays: Math.floor(idle / DAY_MS) };
149
+ }
150
+
151
+ /**
152
+ * The verdict for one cross-factory takeover: `{ ok, missing: [..] }`, `missing` naming each bar
153
+ * not met — 'human' (COLAB_HUMAN=1 with --answered-by) and/or 'stale'. Both are always reported, so
154
+ * one refusal says everything a person has to fix.
155
+ */
156
+ function takeoverVerdict({ colabHuman, answeredBy, stale }) {
157
+ const missing = [];
158
+ if (!(colabHuman && String(answeredBy || '').trim())) missing.push('human');
159
+ if (!stale) missing.push('stale');
160
+ return { ok: missing.length === 0, missing };
161
+ }
162
+
163
+ module.exports = {
164
+ STALE_DAYS, DAY_MS,
165
+ factoryOfMachineName, factoryOfHost, factoryOfLogins, holderComment, holderFactory, isCrossFactory,
166
+ lastActivity, staleness, takeoverVerdict,
167
+ };
@@ -7,6 +7,7 @@ export const RELEASE_MARK: '✅ Released';
7
7
  export const CLAIM_RE: RegExp;
8
8
  export const SESSION_RE: RegExp;
9
9
  export const MACHINE_RE: RegExp;
10
+ export const FACTORY_RE: RegExp;
10
11
  export const YIELD_RE: RegExp;
11
12
 
12
13
  export function looksLikeSessionId(v: unknown): boolean;
@@ -30,6 +31,8 @@ export interface DecodedClaim extends SessionField {
30
31
  at: string;
31
32
  /** `m:` digest (#327), or '' on a legacy comment. */
32
33
  machine: string;
34
+ /** The claiming factory's id (#743, `.github/factories.yml`), or '' where none was named. */
35
+ factory: string;
33
36
  }
34
37
  export function encodeClaim(claim?: Partial<DecodedClaim>): string;
35
38
  export function decodeClaim(body: string | null | undefined): DecodedClaim | null;
@@ -30,6 +30,11 @@ const SESSION_RE = /· session (.+)$/;
30
30
  // SESSION_RE's end anchor both parse a new comment exactly as they parse a legacy one, and a legacy
31
31
  // comment (no such field) simply has no machine and is compared by host.
32
32
  const MACHINE_RE = /· machine `(m:[0-9a-f]{12})`/;
33
+ // #743: the claiming FACTORY (`.github/factories.yml`, #739) — written after the machine and BEFORE
34
+ // the session suffix, for the same reason the machine field sits there: CLAIM_RE's four groups and
35
+ // SESSION_RE's end anchor read a new comment exactly as they read a legacy one, so an older colab
36
+ // parses it unchanged and simply ignores the field. The id grammar is factories.js FACTORY_ID_RE.
37
+ const FACTORY_RE = /· factory `([a-z0-9][a-z0-9-]{0,38})`/;
33
38
  // A yield: the loser of a race releases, naming the winner by its identity string
34
39
  // (`claimIdentity.identityString` — `login@host`, or `login@host#session` under the fine setting).
35
40
  const YIELD_RE = /^✅ Released \(yielded — earlier claim by (.+?) wins\)/;
@@ -102,14 +107,15 @@ function parseIdentity(s) {
102
107
  * (#327, the field is then omitted); `host` is the raw hostname or its `h:` token, whichever the
103
108
  * destination allows (#369 — deciding that is the caller's job, not the codec's).
104
109
  */
105
- function encodeClaim({ worktree, branch, host, at, machine, session, sessionName } = {}) {
110
+ function encodeClaim({ worktree, branch, host, at, machine, factory, session, sessionName } = {}) {
106
111
  const base = `${CLAIM_MARK} — worktree \`${worktree || '-'}\` · branch \`${branch || '-'}\` · host \`${host}\` · ${at}`;
107
112
  const mach = machine ? ` · machine \`${machine}\`` : '';
108
- return base + mach + encodeSessionField(session, sessionName);
113
+ const fac = factory ? ` · factory \`${factory}\`` : ''; // #743 — omitted where no factories file names one
114
+ return base + mach + fac + encodeSessionField(session, sessionName);
109
115
  }
110
116
 
111
117
  /**
112
- * A claim comment body → { worktree, branch, host, at, machine, session, sessionName }, or null when
118
+ * A claim comment body → { worktree, branch, host, at, machine, factory, session, sessionName }, or null when
113
119
  * the body carries no claim. Lenient exactly where the readers always were (CLAIM_RE is unanchored,
114
120
  * a legacy comment simply lacks machine/session), and lossless on what `encodeClaim` writes:
115
121
  * `worktree`/`branch` keep a literal `-` rather than mapping it to empty, so the pair round-trips.
@@ -119,8 +125,12 @@ function decodeClaim(body) {
119
125
  const m = str.match(CLAIM_RE);
120
126
  if (!m) return null;
121
127
  const mm = str.match(MACHINE_RE);
128
+ // #743: the factory is read only BEFORE the session tail — a session name is free text and could
129
+ // itself spell `· factory \`x\``; the writer never puts the field after it.
130
+ const tail = str.match(SESSION_RE);
131
+ const fm = (tail ? str.slice(0, tail.index) : str).match(FACTORY_RE);
122
132
  const { session, sessionName } = parseSessionField(str);
123
- return { worktree: m[1], branch: m[2], host: m[3], at: m[4], machine: mm ? mm[1] : '', session, sessionName };
133
+ return { worktree: m[1], branch: m[2], host: m[3], at: m[4], machine: mm ? mm[1] : '', factory: fm ? fm[1] : '', session, sessionName };
124
134
  }
125
135
 
126
136
  /**
@@ -147,7 +157,7 @@ function decodeRelease(body) {
147
157
  }
148
158
 
149
159
  module.exports = {
150
- CLAIM_MARK, RELEASE_MARK, CLAIM_RE, SESSION_RE, MACHINE_RE, YIELD_RE,
160
+ CLAIM_MARK, RELEASE_MARK, CLAIM_RE, SESSION_RE, MACHINE_RE, FACTORY_RE, YIELD_RE,
151
161
  looksLikeSessionId,
152
162
  encodeSessionField, parseSessionField,
153
163
  encodeIdentity, parseIdentity,
@@ -262,6 +262,7 @@
262
262
  "host": "h:ee4bcb5b2678",
263
263
  "at": "2026-10-05T03:16:29.738Z",
264
264
  "machine": "m:a873b2982c1d",
265
+ "factory": "",
265
266
  "session": "https://claude.ai/code/session_02EXAMPLE00000000000000",
266
267
  "sessionName": "colab-handbook-482"
267
268
  }
@@ -274,6 +275,7 @@
274
275
  "host": "h:ee4bcb5b2678",
275
276
  "at": "2026-10-04T11:53:58.625Z",
276
277
  "machine": "m:a873b2982c1d",
278
+ "factory": "",
277
279
  "session": "https://claude.ai/code/session_03EXAMPLE00000000000000",
278
280
  "sessionName": "colab-handbook-467"
279
281
  }
@@ -286,6 +288,7 @@
286
288
  "host": "h:ee4bcb5b2678",
287
289
  "at": "2026-10-05T11:02:52.482Z",
288
290
  "machine": "m:a873b2982c1d",
291
+ "factory": "",
289
292
  "session": "",
290
293
  "sessionName": "colab-handbook-495"
291
294
  }
@@ -298,6 +301,7 @@
298
301
  "host": "h:48773651d08a",
299
302
  "at": "2026-08-25T02:05:46.075Z",
300
303
  "machine": "",
304
+ "factory": "",
301
305
  "session": "https://claude.ai/code/session_76EXAMPLE00000000000000",
302
306
  "sessionName": ""
303
307
  }
@@ -310,6 +314,7 @@
310
314
  "host": "h:ca0012aa6308",
311
315
  "at": "2026-09-01T11:02:03.931Z",
312
316
  "machine": "",
317
+ "factory": "",
313
318
  "session": "",
314
319
  "sessionName": ""
315
320
  }
@@ -322,6 +327,7 @@
322
327
  "host": "h:ee4bcb5b2678",
323
328
  "at": "2026-09-25T10:48:18.652Z",
324
329
  "machine": "m:a873b2982c1d",
330
+ "factory": "",
325
331
  "session": "https://claude.ai/code/session_14EXAMPLE00000000000000",
326
332
  "sessionName": "colab-handbook-297💻"
327
333
  }
@@ -334,9 +340,24 @@
334
340
  "host": "h:ee4bcb5b2678",
335
341
  "at": "2026-09-13T16:11:15.694Z",
336
342
  "machine": "",
343
+ "factory": "",
337
344
  "session": "https://claude.ai/code/session_40EXAMPLE00000000000000",
338
345
  "sessionName": "colab-handbook-325-326-327"
339
346
  }
347
+ },
348
+ {
349
+ "note": "synthetic (#743): the first claim shape carrying a factory, written in this format before any tracker held one; the factory id is the factories.yml example's",
350
+ "wire": "🔒 Claimed — worktree `claim-factory-743` · branch `feat/claim-factory-743` · host `h:ee4bcb5b2678` · 2026-11-14T10:41:07.512Z · machine `m:a873b2982c1d` · factory `core` · session [colab-handbook-743](https://claude.ai/code/session_05EXAMPLE00000000000000)",
351
+ "decoded": {
352
+ "worktree": "claim-factory-743",
353
+ "branch": "feat/claim-factory-743",
354
+ "host": "h:ee4bcb5b2678",
355
+ "at": "2026-11-14T10:41:07.512Z",
356
+ "machine": "m:a873b2982c1d",
357
+ "factory": "core",
358
+ "session": "https://claude.ai/code/session_05EXAMPLE00000000000000",
359
+ "sessionName": "colab-handbook-743"
360
+ }
340
361
  }
341
362
  ],
342
363
  "releases": [
@@ -55,7 +55,9 @@ const SSH_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)|sk-ssh-e
55
55
 
56
56
  // ── the shared vocabulary (CONVENTIONS.md §5, *Factories*) ──────────────────────────────────
57
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.
58
+ // public surface, and nothing writes these strings yet. #743 writes a factory FIELD on claim comments
59
+ // (codec/claim.js FACTORY_RE), not the `factory:<id>` label, so none of these moved; the first command
60
+ // that writes one of them moves it.
59
61
  const FACTORY_LABEL_PREFIX = 'factory:';
60
62
  const SLICE_LABEL_PREFIX = 'slice:';
61
63
  const QUEUE_READY_LABEL = 'queue:ready';
package/tools/lib/git.js CHANGED
@@ -458,6 +458,12 @@ function parseClaimLockMessage(text) {
458
458
  if (k && out[k] === undefined) out[k] = m[2].trim();
459
459
  }
460
460
  out.colab = out.claimedBy === CLAIM_LOCK_WRITER;
461
+ // #746: the issues the subject names (`claim: #12 #13`) — both writers use this subject. A release
462
+ // that has no recorded lock sha to lease on checks the lock names its issue before deleting it.
463
+ // A `git cat-file commit` body carries headers first; the message starts after the first blank line.
464
+ const message = /^tree [0-9a-f]+$/m.test(s.split('\n')[0]) ? s.slice(s.indexOf('\n\n') + 2) : s;
465
+ const sm = (/^claim:\s*(.*)$/.exec(message.split('\n')[0].trim()) || [])[1];
466
+ out.issues = sm ? [...sm.matchAll(/#(\d+)/g)].map((m) => Number(m[1])).filter((n) => Number.isInteger(n) && n > 0) : [];
461
467
  return out;
462
468
  }
463
469
 
@@ -527,6 +533,17 @@ function releaseClaimLock(repo, remote, num, sha) {
527
533
  return { ok: r.ok, stderr: r.stderr };
528
534
  }
529
535
 
536
+ /**
537
+ * #746 — where `refs/heads/claim/<num>` points on `remote` right now. `{ ok, sha }` (full sha, or
538
+ * `null` when there is no lock) or `{ ok: false, stderr }` when the remote could not be asked.
539
+ */
540
+ function remoteClaimLock(repo, remote, num) {
541
+ const ls = git(['ls-remote', remote, claimLockRef(num)], repo, { timeoutMs: 60_000 });
542
+ if (!ls.ok) return { ok: false, stderr: ls.stderr || (ls.timedOut ? 'ls-remote timed out' : `exit ${ls.code}`) };
543
+ const sha = (String(ls.stdout || '').split(/\s+/)[0] || '').trim();
544
+ return { ok: true, sha: sha || null };
545
+ }
546
+
530
547
  /**
531
548
  * Read who holds a lock: the commit at `fullSha`, fetched from `remote` when this clone lacks it.
532
549
  * `{ ok, trailers }` (`parseClaimLockMessage`) or `{ ok: false, stderr }` — a failed read is the
@@ -543,6 +560,28 @@ function readClaimLock(repo, remote, num, fullSha) {
543
560
  return { ok: true, trailers: parseClaimLockMessage(body.stdout) };
544
561
  }
545
562
 
563
+ /**
564
+ * #744 — the committer time (ms) of the commit a remote ref points at, or null when it cannot be read.
565
+ * `ref` is the full remote ref (`refs/heads/<b>`, `refs/claims/<b>`, `refs/heads/claim/<N>`); `sha`
566
+ * (short or full) is what `ls-remote` saw. Read locally when this clone has the commit, else fetched
567
+ * by ref name. A null is the caller's to treat as "recent" (fail closed: an unreadable holder is
568
+ * never proven stale).
569
+ */
570
+ function remoteRefCommitTime(repo, remote, ref, sha) {
571
+ const at = (rev) => {
572
+ const r = git(['log', '-1', '--format=%ct', rev, '--'], repo);
573
+ const n = r.ok ? Number(String(r.stdout).trim()) : NaN;
574
+ return Number.isFinite(n) && n > 0 ? n * 1000 : null;
575
+ };
576
+ if (sha) {
577
+ const local = git(['cat-file', '-e', `${sha}^{commit}`], repo);
578
+ if (local.ok) return at(sha);
579
+ }
580
+ const f = git(['fetch', '--quiet', '--no-tags', remote, ref], repo, { timeoutMs: 60_000 });
581
+ if (!f.ok) return null;
582
+ return at('FETCH_HEAD');
583
+ }
584
+
546
585
  /** List worktree paths registered in a repo (porcelain). */
547
586
  function worktreeList(repo) {
548
587
  const r = git(['worktree', 'list', '--porcelain'], repo);
@@ -1859,7 +1898,7 @@ module.exports = {
1859
1898
  detectTrunk, branchExists, branchRefs, existingBranchRef,
1860
1899
  claimRemote, remoteHeads, parseRemoteHeads, CLAIM_REF_PREFIX, claimRef, pushClaimRef, deleteClaimRef,
1861
1900
  CLAIM_LOCK_PREFIX, claimLockRef, parseClaimLocks, claimLockMessage, parseClaimLockMessage, makeClaimLockCommit,
1862
- takeClaimLocks, releaseClaimLock, readClaimLock,
1901
+ takeClaimLocks, releaseClaimLock, readClaimLock, remoteClaimLock, remoteRefCommitTime,
1863
1902
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1864
1903
  dirtyTracked, dirtyUntracked, dirtyAny,
1865
1904
  ghAvailable, ghState, ghInstalled, ghApiConditional, ghRunsAtShaRest, ghRunsAtShaUnfiltered, fullSha, ghIssueEdit, ghListLabels, ghOpenIssueNumbersByLabel, ghAssignedIssues,
@@ -42,6 +42,11 @@
42
42
  * 7. every issue the branch carries has a LIVE `🔒 Claimed` comment naming this branch, posted by
43
43
  * the hand-off's author before the hand-off — the claim really does live elsewhere, and the
44
44
  * party handing off is the party holding it.
45
+ * #743: "the party" is login AND factory. Where the hand-off's `colab:handoff` marker names a
46
+ * factory (`factory=<id>`) and the claim names one too, they must be the same factory: two teams
47
+ * may share one forge login (`.github/factories.yml`, #739), and the same login under another
48
+ * factory is another holder. Either side naming none (a pre-#743 writer, a repo with no
49
+ * factories file) compares by login alone, as before.
45
50
  * ONE exemption (#647): an issue the trailing run carries that was already CLOSED before the
46
51
  * hand-off was posted only names history (a flaky test named after it) — it needs no claim, and
47
52
  * goes back in `refIssues` so the squash says `Refs #A` and ship neither closes it nor posts a
@@ -95,6 +100,36 @@ function namesBranch(body, branch) {
95
100
  return new RegExp(`(^|[^A-Za-z0-9._/-])${escapeRe(branch)}(?![A-Za-z0-9._/-])`).test(String(body || ''));
96
101
  }
97
102
 
103
+ /**
104
+ * #685/#743 — the hand-off marker code-wrap opens the comment with:
105
+ * `<!-- colab:handoff branch=<branch> head=<full sha> [factory=<id>] -->` → `{ branch, head, factory,
106
+ * fields }` (`factory` '' when absent), or null when the body holds none. Fields are space-separated
107
+ * `key=value` pairs in any order; a value holds no space. When a body holds several markers the LAST
108
+ * one wins — a later hand-off on the same thread supersedes an earlier one.
109
+ */
110
+ function parseHandoffMarker(body) {
111
+ const all = [...String(body || '').matchAll(/<!--\s*colab:handoff((?:\s+[A-Za-z][\w-]*=\S+?)*)\s*-->/g)];
112
+ if (!all.length) return null;
113
+ const fields = {};
114
+ for (const kv of all[all.length - 1][1].trim().split(/\s+/).filter(Boolean)) {
115
+ const i = kv.indexOf('=');
116
+ fields[kv.slice(0, i)] = kv.slice(i + 1);
117
+ }
118
+ return { branch: fields.branch || '', head: (fields.head || '').toLowerCase(), factory: fields.factory || '', fields };
119
+ }
120
+
121
+ /** #743 — the marker line for a hand-off. `factory` is omitted when '' (no factories file names one). */
122
+ function formatHandoffMarker({ branch, head, factory }) {
123
+ return `<!-- colab:handoff branch=${branch} head=${head}${factory ? ` factory=${factory}` : ''} -->`;
124
+ }
125
+
126
+ /** #743 — may `claim` (a live claim entry) and a hand-off naming `factory` be the same holder's? */
127
+ function sameFactory(claimFactory, handoffFactory) {
128
+ const a = String(claimFactory || '').trim();
129
+ const b = String(handoffFactory || '').trim();
130
+ return !a || !b || a === b;
131
+ }
132
+
98
133
  /** Every 7–40 hex token in `body`, lower-cased — the candidate head shas a hand-off names. */
99
134
  function namedShas(body) {
100
135
  return [...String(body || '').matchAll(/(?<![0-9A-Za-z])([0-9a-fA-F]{7,40})(?![0-9A-Za-z])/g)]
@@ -161,12 +196,20 @@ function handoffVerdict({ url, comment, branch, refs, claimsByIssue, syncChain,
161
196
  return no('nothing-to-close', `every issue ${branch} carries (${issues.map((n) => '#' + n).join(' ')}) was closed before the hand-off — there is no open, claimed issue for it to land`);
162
197
  }
163
198
  const waived = new Set((refNumbers || []).map(Number));
199
+ const handoffFactory = (parseHandoffMarker(comment.body) || {}).factory || '';
164
200
  let executor = null;
165
201
  for (const n of issues) {
166
202
  if (refIssues.includes(n)) continue;
167
203
  const live = claimsByIssue ? claimsByIssue[n] : null;
168
204
  if (!live) return no('claims-unreadable', `#${n}'s comments could not be read — the executor's claim cannot be checked`);
169
- const match = live.find((c) => c.branch === branch && c.login === comment.login && c.at < comment.createdAt);
205
+ const byLogin = live.filter((c) => c.branch === branch && c.login === comment.login && c.at < comment.createdAt);
206
+ const match = byLogin.find((c) => sameFactory(c.factory, handoffFactory));
207
+ if (!match && byLogin.length) {
208
+ // #743: the login holds it, but under another factory — a different holder handing off.
209
+ const other = [...new Set(byLogin.map((c) => c.factory))].join(', ');
210
+ return no('other-factory-claim', `#${n}'s live 🔒 claim on ${branch} by ${comment.login} names factory ${other}, but the hand-off names factory ${handoffFactory} — ` +
211
+ 'the same login under another factory is another holder; the hand-off must come from the factory holding the claim');
212
+ }
170
213
  if (!match) {
171
214
  const st = issueStates && issueStates[n];
172
215
  const why = st && String(st.state).toUpperCase() === 'CLOSED'
@@ -175,7 +218,7 @@ function handoffVerdict({ url, comment, branch, refs, claimsByIssue, syncChain,
175
218
  return no('no-executor-claim', `#${n} has no live 🔒 claim on ${branch} by ${comment.login || 'the hand-off author'} posted before the hand-off${why} — ` +
176
219
  'the hand-off must come from the party holding the claim');
177
220
  }
178
- if (!executor) executor = { login: match.login, host: match.host, machine: match.machine || '' };
221
+ if (!executor) executor = { login: match.login, host: match.host, machine: match.machine || '', factory: match.factory || handoffFactory || '' };
179
222
  }
180
223
  return { ok: true, issues, refIssues, sha: refs.remoteSha, handedOff: lineage[at], syncMerges: at, executor, url: String(url).trim(),
181
224
  ref: formatHandoffRef(got), htmlUrl: comment.htmlUrl };
@@ -277,4 +320,4 @@ function parseHandoffTrailer(body) {
277
320
  return m ? { url: m[1], handedOff: m[2] } : null;
278
321
  }
279
322
 
280
- module.exports = { parseHandoffUrl, parseHandoffRef, formatHandoffRef, namesBranch, namedShas, handoffVerdict, closedBefore, handoffTrailer, syncMergeChain, parseBatchEntries, parseHandoffTrailer };
323
+ module.exports = { parseHandoffUrl, parseHandoffRef, formatHandoffRef, parseHandoffMarker, formatHandoffMarker, sameFactory, namesBranch, namedShas, handoffVerdict, closedBefore, handoffTrailer, syncMergeChain, parseBatchEntries, parseHandoffTrailer };