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

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.5"
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
 
@@ -765,9 +821,9 @@ function settleTrackerPending(repoAbs, nums, missed, owner) {
765
821
  * login+host is invisible to the check above. Read the comments too and look for exactly that.
766
822
  * A read failure (null) is skipped, never treated as free.
767
823
  */
768
- function ghClaimConflicts(repoAbs, nums, myLogin, myHost, mySession, comps, myMachine = null) {
824
+ function ghClaimConflicts(repoAbs, nums, myLogin, myHost, mySession, comps, myMachine = null, myFactoryId = '') {
769
825
  comps = comps || claimIdentity.DEFAULT_COMPONENTS;
770
- const me = { login: myLogin, host: myHost, session: mySession || '', machine: myMachine || '' };
826
+ const me = { login: myLogin, host: myHost, session: mySession || '', machine: myMachine || '', factory: myFactoryId || '' };
771
827
  const out = [];
772
828
  for (const num of nums) {
773
829
  const info = git.ghIssueView(repoAbs, num, ['assignees', 'labels', 'comments']);
@@ -792,6 +848,11 @@ function ghClaimConflicts(repoAbs, nums, myLogin, myHost, mySession, comps, myMa
792
848
  // different place to hold work in, while a session knob only ever distinguished co-tenants.
793
849
  {
794
850
  const live = liveClaimComments(info.comments || [], comps);
851
+ // #743: OUR OWN login held by ANOTHER FACTORY — two teams on one forge login (#739). The
852
+ // assignee set says nothing about it, and the machine check below may not either (two teams'
853
+ // machines can share a hostname). Checked first: it is the more specific finding.
854
+ const otherFactory = live.find((c) => c.login === myLogin && !claimIdentity.sameFactory(c, me));
855
+ if (otherFactory) { out.push({ num, assignees, otherFactory }); continue; }
795
856
  const other = live.find((c) => c.login === myLogin && !claimIdentity.sameHost(c, me));
796
857
  if (other) { out.push({ num, assignees, otherMachine: other }); continue; }
797
858
  }
@@ -839,7 +900,11 @@ function printRefusal(localConf, ghConf, remoteConf = []) {
839
900
  ` #${c.num} local: worktree "${h.worktree || '-'}" · branch ${h.branch || '-'} · host ${h.host}${sess} · since ${String(h.created).slice(0, 10)}\n`);
840
901
  }
841
902
  for (const c of ghConf) {
842
- if (c.otherMachine) {
903
+ if (c.otherFactory) {
904
+ const o = c.otherFactory;
905
+ const id = displayIdentity(o.sessionName, o.session);
906
+ 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`);
907
+ } else if (c.otherMachine) {
843
908
  const o = c.otherMachine;
844
909
  const id = displayIdentity(o.sessionName, o.session);
845
910
  process.stderr.write(` #${c.num} GitHub: live claim comment from another machine (host ${o.host}${id ? ` · session ${id}` : ''}) — same account (#325)\n`);
@@ -876,7 +941,9 @@ function printTakeover(localConf, ghConf, remoteConf = []) {
876
941
  print(` --force: taking over #${c.num} from worktree "${h.worktree || '-'}" (host ${h.host}${sess}, since ${String(h.created).slice(0, 10)})`);
877
942
  }
878
943
  for (const c of ghConf) {
879
- if (c.otherMachine) {
944
+ if (c.otherFactory) {
945
+ print(` --force: taking over #${c.num} from factory ${c.otherFactory.factory}'s claim under this account (host ${c.otherFactory.host}, #743)`);
946
+ } else if (c.otherMachine) {
880
947
  print(` --force: taking over #${c.num} from this account's claim on another machine (host ${c.otherMachine.host})`);
881
948
  } else if (c.cotenant) {
882
949
  const id = displayIdentity(c.cotenant.sessionName, c.cotenant.session) || c.cotenant.identity;
@@ -889,9 +956,113 @@ function printTakeover(localConf, ghConf, remoteConf = []) {
889
956
  }
890
957
  }
891
958
 
959
+ /**
960
+ * #744 — `.github/factories.yml` as committed on trunk (`<remote>/<trunk>`, else local `<trunk>`),
961
+ * fetched first so a file landed since this clone's last fetch is not missed. Never the checkout's
962
+ * or a branch's copy: a branch that could edit the file could make itself the holder's factory.
963
+ * `{ present, ref, parsed? }`.
964
+ */
965
+ function factoriesAtTrunk(repoAbs) {
966
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
967
+ if (!trunk) return { present: false, ref: null };
968
+ let remote = null;
969
+ try { remote = git.claimRemote(repoAbs); } catch (_) { remote = null; }
970
+ if (remote) git.git(['fetch', '--quiet', '--no-tags', remote, trunk], repoAbs, { timeoutMs: 60_000 });
971
+ for (const ref of [remote ? `${remote}/${trunk}` : null, trunk].filter(Boolean)) {
972
+ if (!git.git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], repoAbs).ok) continue;
973
+ const r = git.git(['show', `${ref}:${factoriesLib.PATH}`], repoAbs);
974
+ if (!r.ok) return { present: false, ref };
975
+ return { present: true, ref, parsed: factoriesLib.parseFactories(r.stdout) };
976
+ }
977
+ return { present: false, ref: null };
978
+ }
979
+
980
+ /**
981
+ * #744 — the cross-factory bar on a `--force` takeover, shared by `colab claim` and `colab worktree
982
+ * new --issues`. Runs only once `--force` was given over a refusal. For every issue whose holder is
983
+ * not proven to be this machine's factory (tools/lib/claim-takeover.js `isCrossFactory`), the
984
+ * takeover needs the holder STALE (no activity for claimTakeover.STALE_DAYS days) AND a human
985
+ * (`COLAB_HUMAN=1` with `--answered-by`). No factories file on trunk → `{ ok: true, cross: [] }`,
986
+ * exactly the behaviour before this. Prints its own refusal; the caller only returns 1.
987
+ */
988
+ function crossFactoryGate(repoAbs, nums, { localConf = [], ghConf = [], remoteConf = [], answeredBy = null } = {}) {
989
+ const file = factoriesAtTrunk(repoAbs);
990
+ if (!file.present) return { ok: true, cross: [] };
991
+ const mine = claimTakeover.factoryOfMachineName(file.parsed, HOST);
992
+ const colabHuman = process.env.COLAB_HUMAN === '1';
993
+ const nowMs = Date.now();
994
+ const cross = [];
995
+ const refused = [];
996
+ for (const num of nums) {
997
+ const holders = [
998
+ ...remoteConf.filter((c) => c.num === num).map((c) => ({ kind: 'remote', c })),
999
+ ...ghConf.filter((c) => c.num === num).map((c) => ({ kind: 'gh', c })),
1000
+ ];
1001
+ if (!holders.length) continue; // only this machine's own state holds it (or nothing does)
1002
+ const factoriesOf = holders.map((h) => claimTakeover.holderFactory(file.parsed, h.kind, h.c, mine));
1003
+ if (!claimTakeover.isCrossFactory(file, mine, factoriesOf)) continue;
1004
+ const times = [];
1005
+ for (const { kind, c } of holders) {
1006
+ if (kind === 'remote') {
1007
+ const ref = c.lock ? git.claimLockRef(num) : c.claimRef ? git.claimRef(c.branch) : `refs/heads/${c.branch}`;
1008
+ times.push(git.remoteRefCommitTime(repoAbs, c.remote, ref, c.fullSha || c.sha));
1009
+ } else {
1010
+ const cm = claimTakeover.holderComment(c);
1011
+ times.push(cm && cm.at ? Date.parse(cm.at) : null);
1012
+ }
1013
+ }
1014
+ const last = claimTakeover.lastActivity(times);
1015
+ const st = claimTakeover.staleness(last, nowMs);
1016
+ const holderFactory = [...new Set(factoriesOf.filter(Boolean))].join(', ') || null;
1017
+ const v = claimTakeover.takeoverVerdict({ colabHuman, answeredBy, stale: st.stale });
1018
+ const row = { num, mine, holderFactory, last, idleDays: st.idleDays, missing: v.missing, valid: !!(file.parsed && file.parsed.valid) };
1019
+ cross.push(row);
1020
+ if (!v.ok) refused.push(row);
1021
+ }
1022
+ if (refused.length) {
1023
+ 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`);
1024
+ for (const r of refused) {
1025
+ 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]})`;
1026
+ 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)';
1027
+ process.stderr.write(` #${r.num} held by ${who}; this machine is ${r.mine ? `factory ${r.mine}` : 'in no factory'}; ${since}\n`);
1028
+ 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`);
1029
+ 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');
1030
+ }
1031
+ return { ok: false, cross };
1032
+ }
1033
+ for (const r of cross) {
1034
+ 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)`);
1035
+ }
1036
+ return { ok: true, cross };
1037
+ }
1038
+
1039
+ /**
1040
+ * #744 — after a `--force` takeover has taken the locks: remove the displaced holder's legacy claim
1041
+ * refs (`refs/claims/<branch>`, #550). The lock itself was already overwritten under a lease on the
1042
+ * holder's sha; a real branch is never deleted — it carries commits. A cross-factory takeover also
1043
+ * leaves one comment on the issue naming who answered for it. Best effort, like every other
1044
+ * release-side write: a failure warns with the command.
1045
+ */
1046
+ function afterForcedTakeover(repoAbs, remoteConf, cross, answeredBy) {
1047
+ const seen = new Set();
1048
+ for (const c of remoteConf || []) {
1049
+ if (!c.claimRef || seen.has(c.branch)) continue;
1050
+ seen.add(c.branch);
1051
+ const r = git.deleteClaimRef(repoAbs, c.remote, c.branch);
1052
+ if (r.ok && !r.absent) print(` removed the displaced holder's claim ref ${c.remote} ${git.claimRef(c.branch)} (#744)`);
1053
+ 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)}`);
1054
+ }
1055
+ for (const r of cross || []) {
1056
+ const body = `⚠️ Cross-factory takeover (#744): this claim, held by ${r.holderFactory ? `factory \`${r.holderFactory}\`` : 'a holder no record ties to a factory'} ` +
1057
+ `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).`;
1058
+ const c = git.ghIssueComment(repoAbs, r.num, body);
1059
+ if (!c.ok) warn(`could not post the takeover note on #${r.num} (${String(c.stderr || '').split('\n')[0] || c.code})`);
1060
+ }
1061
+ }
1062
+
892
1063
  /** Post the claim comment (best-effort: a failure warns but never fails the claim). */
893
1064
  function postClaimComment(repoAbs, num, wtName, branch, session, sessionName) {
894
- const r = git.ghIssueComment(repoAbs, num, claimCommentBody(wtName, branch, session, sessionName, commentHost(repoAbs)));
1065
+ const r = git.ghIssueComment(repoAbs, num, claimCommentBody(wtName, branch, session, sessionName, commentHost(repoAbs), myFactory(repoAbs)));
895
1066
  if (!r.ok) warn(`could not post claim comment on #${num} (${r.stderr.split('\n')[0] || r.code}) — claim stands`);
896
1067
  }
897
1068
 
@@ -1004,7 +1175,7 @@ function commentAndTieBreak(repoAbs, nums, owner) {
1004
1175
  postClaimComment(repoAbs, num, owner.wtName, owner.branch, owner.session, owner.sessionName);
1005
1176
  const info = git.ghIssueView(repoAbs, num, ['comments']);
1006
1177
  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());
1178
+ const verdict = tieBreakVerdict(info.comments, owner.myLogin, HOST, owner.session, comps, myMachineId(), myFactory(repoAbs));
1008
1179
  if (verdict.lost) {
1009
1180
  yieldIssue(repoAbs, num, verdict.winner, owner.myLogin, owner.session || null);
1010
1181
  const w = verdict.winner;
@@ -1096,12 +1267,20 @@ Options:
1096
1267
  (never probed — a human lead only). Default: auto-detect (an agent session's
1097
1268
  long-lived process, verified alive + a proven ancestor; else the parent shell,
1098
1269
  exactly as before). Also settable via COLAB_PLACE_PID.
1099
- --force take over a claim held by another worktree / GitHub user (logged, never silent)
1270
+ --force take over a claim held by another worktree / GitHub user (logged, never silent).
1271
+ The displaced holder's legacy claim ref (refs/claims/<branch>) is removed; its
1272
+ lock is overwritten; a branch with commits is never deleted (#744).
1273
+ ANOTHER FACTORY's claim (.github/factories.yml on trunk — any foreign holder not
1274
+ proven to be this machine's factory, and every holder when the file is invalid)
1275
+ needs BOTH: no activity on the claim for 5 days (the newest of the commits on
1276
+ its lock, claim ref or branch and its claim comments) AND a human — COLAB_HUMAN=1
1277
+ with --answered-by. No factories file → unchanged (#744).
1278
+ --answered-by <n> with COLAB_HUMAN=1 and --force: the human who answers for a cross-factory takeover
1100
1279
  `;
1101
1280
 
1102
1281
  function cmdClaim(argv) {
1103
1282
  const opts = parseArgs(argv, {
1104
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--session': 'session', '--session-name': 'sessionName', '--pid': 'pid' },
1283
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--session': 'session', '--session-name': 'sessionName', '--pid': 'pid', '--answered-by': 'answeredBy' },
1105
1284
  flags: { '--force': 'force', '-h': 'help', '--help': 'help' },
1106
1285
  });
1107
1286
  if (opts.help || opts._.length === 0) return print(HELP_CLAIM);
@@ -1180,10 +1359,14 @@ function cmdClaim(argv) {
1180
1359
  if (remoteCheck.mode === 'no-remote') warn('no git remote — this claim is recorded on this machine only; no other machine can see it');
1181
1360
  const remoteConf = remoteCheck.conflicts;
1182
1361
  const localConf = localClaimConflicts(st0, repoAbs, nums, wtName);
1183
- const ghConf = gh ? ghClaimConflicts(repoAbs, nums, myLogin, HOST, session, comps, myMachineId()) : [];
1362
+ const ghConf = gh ? ghClaimConflicts(repoAbs, nums, myLogin, HOST, session, comps, myMachineId(), myFactory(repoAbs)) : [];
1184
1363
  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`);
1364
+ let crossTakeover = [];
1185
1365
  if (remoteConf.length || localConf.length || ghConf.length) {
1186
1366
  if (!opts.force) { printRefusal(localConf, ghConf, remoteConf); return 1; }
1367
+ const gate = crossFactoryGate(repoAbs, nums, { localConf, ghConf, remoteConf, answeredBy: opts.answeredBy || null });
1368
+ if (!gate.ok) return 1;
1369
+ crossTakeover = gate.cross;
1187
1370
  printTakeover(localConf, ghConf, remoteConf);
1188
1371
  }
1189
1372
 
@@ -1238,6 +1421,7 @@ function cmdClaim(argv) {
1238
1421
  if (lockTake.taken.includes(num)) print(` took claim lock ${remoteCheck.remote} ${l.ref} (#741)`);
1239
1422
  else if (l.adopted) print(` claim lock ${remoteCheck.remote} ${l.ref} was already taken on this machine for this work — adopted (#741)`);
1240
1423
  }
1424
+ if (opts.force && (remoteConf.length || crossTakeover.length)) afterForcedTakeover(repoAbs, remoteConf, crossTakeover, opts.answeredBy || null);
1241
1425
 
1242
1426
  // #389: measured outside the lock (git, not state) — see the attach branch inside the mutation.
1243
1427
  const existingDir = wtName ? existingWorktreeFor(repoAbs, wtName, branch) : null;
@@ -6048,7 +6232,9 @@ dependency symlinking, dev-server restarts) live in OPTIONAL repo hooks, not her
6048
6232
  --session-name <s> short human label for tables/messages (env COLAB_SESSION_NAME)
6049
6233
  --pid <n|none> the new worktree's place-claim liveness anchor (#288) — same meaning as
6050
6234
  \`colab claim\`'s --pid; default: auto-detect (env COLAB_PLACE_PID too)
6051
- --force take over issues already claimed by another worktree / GitHub user
6235
+ --force take over issues already claimed by another worktree / GitHub user —
6236
+ another factory's claim needs a 5-day-stale holder AND COLAB_HUMAN=1 with
6237
+ --answered-by <name>, exactly as 'colab claim --force' (see colab claim -h, #744)
6052
6238
  Claimed issues are ENFORCED: if --issues names an issue already held (locally on another
6053
6239
  worktree, or on GitHub by someone else) the command REFUSES before building anything,
6054
6240
  unless --force. On success each issue gets a "🔒 Claimed" comment + the tie-break runs;
@@ -6250,7 +6436,7 @@ function uncommittedWork(wtPath) {
6250
6436
 
6251
6437
  function cmdWorktreeNew(argv) {
6252
6438
  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' },
6439
+ 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
6440
  aliases: { '--issue': '--issues' },
6255
6441
  flags: { '--force': 'force', '-h': 'help', '--help': 'help' },
6256
6442
  });
@@ -6296,6 +6482,7 @@ function cmdWorktreeNew(argv) {
6296
6482
 
6297
6483
  // ---- REFUSAL: don't build a worktree around issues someone else already holds ----
6298
6484
  let remoteCheck = null;
6485
+ let crossTakeover = [];
6299
6486
  if (issues.length) {
6300
6487
  const st0 = state.loadState();
6301
6488
  // #325: the remote first — the branch on it is the claim record every machine reads.
@@ -6303,10 +6490,13 @@ function cmdWorktreeNew(argv) {
6303
6490
  if (remoteCheck.mode === 'unreachable') { printRemoteUnreachable(remoteCheck, 'worktree and its claims'); return 1; }
6304
6491
  if (remoteCheck.mode === 'no-remote') warn('no git remote — these claims are recorded on this machine only; no other machine can see them');
6305
6492
  const localConf = localClaimConflicts(st0, repoAbs, issues, name);
6306
- const ghConf = gh ? ghClaimConflicts(repoAbs, issues, myLogin, HOST, session, comps, myMachineId()) : [];
6493
+ const ghConf = gh ? ghClaimConflicts(repoAbs, issues, myLogin, HOST, session, comps, myMachineId(), myFactory(repoAbs)) : [];
6307
6494
  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
6495
  if (remoteCheck.conflicts.length || localConf.length || ghConf.length) {
6309
6496
  if (!opts.force) { printRefusal(localConf, ghConf, remoteCheck.conflicts); return 1; }
6497
+ const gate = crossFactoryGate(repoAbs, issues, { localConf, ghConf, remoteConf: remoteCheck.conflicts, answeredBy: opts.answeredBy || null });
6498
+ if (!gate.ok) return 1;
6499
+ crossTakeover = gate.cross;
6310
6500
  printTakeover(localConf, ghConf, remoteCheck.conflicts);
6311
6501
  }
6312
6502
  }
@@ -6410,6 +6600,7 @@ function cmdWorktreeNew(argv) {
6410
6600
  else if (l.adopted) print(` claim lock ${remoteCheck.remote} ${l.ref} was already taken on this machine for this work — adopted (#741)`);
6411
6601
  else print(` claim lock ${remoteCheck.remote} ${l.ref} is already this machine's — kept`);
6412
6602
  }
6603
+ if (opts.force && remoteCheck && (remoteCheck.conflicts.length || crossTakeover.length)) afterForcedTakeover(repoAbs, remoteCheck.conflicts, crossTakeover, opts.answeredBy || null);
6413
6604
 
6414
6605
  // How far behind trunk the line is, as INFORMATION — never a threshold. A long-lived line is
6415
6606
  // expected to diverge; a refusal (or a warning with a number in it) would fire on every healthy
@@ -14793,7 +14984,8 @@ function applyShipHandoff(repoAbs, sess, opts, trunk) {
14793
14984
  sess.handoffRefs = new Set(v.refIssues || []);
14794
14985
  // #372: the implementer is the executor that handed off — name it, never leave it reading as the shipper.
14795
14986
  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);
14987
+ const ex = (claimsByIssue[claimed] || []).find((c) => c.branch === sess.branch && c.login === v.executor.login
14988
+ && shipHandoff.sameFactory(c.factory, v.executor.factory)); // #743: the same login under another factory is another holder
14797
14989
  if (ex && (ex.session || ex.sessionName)) sess.holder = { session: ex.session || '', sessionName: ex.sessionName || '' };
14798
14990
  return v;
14799
14991
  }
@@ -18075,6 +18267,44 @@ function cmdInstructionFiles(argv) {
18075
18267
  return 0;
18076
18268
  }
18077
18269
 
18270
+ const HELP_FACTORY = `colab factory [--repo <path>] [--json]
18271
+
18272
+ This machine's FACTORY in a repo (#743): the id \`.github/factories.yml\` (#739), as committed on
18273
+ TRUNK, lists this machine under — the id a 🔒 claim comment written from here carries
18274
+ (\`· factory \\\`<id>\\\`\`) and the one code-wrap's hand-off marker names (\`factory=<id>\`).
18275
+ The machine is looked up by its label (the hostname's first label, lower-cased, \`[a-z0-9-]\` only),
18276
+ the name the claim lock's \`Machine:\` trailer carries.
18277
+
18278
+ exit 0 the file lists this machine; prints the id
18279
+ exit 1 no factories file on trunk (one team — name no factory), the file is invalid
18280
+ (it names nobody), or it does not list this machine — prints why, on stderr
18281
+ --json { factory, reason: listed|no-file|invalid|unlisted, machine, ref, findings? }
18282
+ `;
18283
+
18284
+ function cmdFactory(argv) {
18285
+ const opts = parseArgs(argv, {
18286
+ values: { '--repo': 'repo' },
18287
+ flags: { '--json': 'json', '-h': 'help', '--help': 'help' },
18288
+ });
18289
+ if (opts.help) return print(HELP_FACTORY);
18290
+ const repoAbs = resolveRepo(opts);
18291
+ if (!git.repoRoot(repoAbs)) throw new UserError(`${repoAbs} is not a git repo — run it inside the repo, or pass --repo <path>`);
18292
+ const f = factoryFor(repoAbs);
18293
+ if (opts.json) {
18294
+ print(JSON.stringify({ factory: f.id || null, reason: f.reason, machine: f.machine, ref: f.ref || null,
18295
+ ...(f.findings && f.findings.length ? { findings: f.findings } : {}) }, null, 2));
18296
+ return f.id ? 0 : 1;
18297
+ }
18298
+ if (f.id) { print(f.id); return 0; }
18299
+ const why = {
18300
+ 'no-file': `no ${factories.PATH} on trunk — one team; a claim names no factory`,
18301
+ invalid: `${factories.PATH} on ${f.ref} is invalid — it names nobody (${(f.findings || [])[0] || 'see colab audit'})`,
18302
+ unlisted: `${factories.PATH} on ${f.ref} lists no factory for machine "${f.machine}"`,
18303
+ }[f.reason] || f.reason;
18304
+ process.stderr.write(`colab factory: ${why}\n`);
18305
+ return 1;
18306
+ }
18307
+
18078
18308
  function cmdHolders(argv) {
18079
18309
  const opts = parseArgs(argv, {
18080
18310
  values: { '--repo': 'repo', '--base': 'base' },
@@ -18763,6 +18993,9 @@ Commands:
18763
18993
  holders <path> [--base B] [--json] who else is holding <path> — refs that touched it and
18764
18994
  have not landed on the base (filters the raw git-log
18765
18995
  one-liner through \`landed\`'s content classification)
18996
+ factory [--json] this machine's factory in the repo, from trunk's
18997
+ .github/factories.yml (#743) — what a claim and a
18998
+ hand-off marker name
18766
18999
  instruction-files [--base B | --staged] [--json]
18767
19000
  CLAUDE.md is only @AGENTS.md + tool blocks? ratcheted:
18768
19001
  fails only where the change touches it or would regress
@@ -18859,6 +19092,7 @@ function main(argv) {
18859
19092
  case 'trunk-ci': return cmdTrunkCi(rest);
18860
19093
  case 'ci-wait': return cmdCiWait(rest);
18861
19094
  case 'holders': return cmdHolders(rest);
19095
+ case 'factory': return cmdFactory(rest);
18862
19096
  case 'instruction-files': return cmdInstructionFiles(rest);
18863
19097
  case 'promote': return cmdPromote(rest);
18864
19098
  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
@@ -159,9 +159,25 @@ function machineScheme(id) {
159
159
  return i === -1 ? '' : id.slice(0, i);
160
160
  }
161
161
 
162
+ /**
163
+ * Could `a` and `b` be the SAME factory (#743)? Two teams may work one repository under one forge
164
+ * login (`.github/factories.yml`, #739), so a login match alone no longer names a holder: a claim
165
+ * that names factory `x` and one that names `y` are two holders, whatever login posted them. Like
166
+ * the session (DEGRADE-ON-MISSING above), the factory decides only when BOTH sides carry one — a
167
+ * comment written before #743, or on a repository with no factories file, names none, and must not
168
+ * turn our own earlier claim into a stranger's. Not behind the claimIdentity knob: the factories
169
+ * file is itself the adopter's declaration that factories are distinct holders.
170
+ */
171
+ function sameFactory(a, b) {
172
+ const af = String((a && a.factory) || '').trim();
173
+ const bf = String((b && b.factory) || '').trim();
174
+ return !af || !bf || af === bf;
175
+ }
176
+
162
177
  /**
163
178
  * 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`
179
+ * always required to match — they are the baseline every component set includes — and so is the
180
+ * factory where both name one (`sameFactory`, #743). `session`
165
181
  * sharpens the match ONLY when `comps` includes it AND both sides carry a non-empty value that is a
166
182
  * real session; either side blank, or either side a planner intent id (#326 — replaced by the real
167
183
  * session at spawn, so it is not a different claimant), degrades that pair back to the coarse
@@ -170,6 +186,7 @@ function machineScheme(id) {
170
186
  function sameClaimant(a, b, comps) {
171
187
  if (!a || !b) return false;
172
188
  if ((a.login || '') !== (b.login || '')) return false;
189
+ if (!sameFactory(a, b)) return false;
173
190
  if (!sameHost(a, b)) return false;
174
191
  if (comps && comps.includes('session') && a.session && b.session
175
192
  && !isIntentSession(a.session) && !isIntentSession(b.session)) {
@@ -227,6 +244,6 @@ const { looksLikeSessionId } = require('./codec/claim'); // one copy of the rule
227
244
  module.exports = {
228
245
  DEFAULT_COMPONENTS, FINE_COMPONENTS,
229
246
  claimIdentityProblem, components, identityString, sameClaimant, mergeClaimRecord,
230
- looksLikeSessionId, isIntentSession, sameHost,
247
+ looksLikeSessionId, isIntentSession, sameHost, sameFactory,
231
248
  shouldDerivePersonSession, derivePersonSession, isPersonSession,
232
249
  };
@@ -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
@@ -543,6 +543,28 @@ function readClaimLock(repo, remote, num, fullSha) {
543
543
  return { ok: true, trailers: parseClaimLockMessage(body.stdout) };
544
544
  }
545
545
 
546
+ /**
547
+ * #744 — the committer time (ms) of the commit a remote ref points at, or null when it cannot be read.
548
+ * `ref` is the full remote ref (`refs/heads/<b>`, `refs/claims/<b>`, `refs/heads/claim/<N>`); `sha`
549
+ * (short or full) is what `ls-remote` saw. Read locally when this clone has the commit, else fetched
550
+ * by ref name. A null is the caller's to treat as "recent" (fail closed: an unreadable holder is
551
+ * never proven stale).
552
+ */
553
+ function remoteRefCommitTime(repo, remote, ref, sha) {
554
+ const at = (rev) => {
555
+ const r = git(['log', '-1', '--format=%ct', rev, '--'], repo);
556
+ const n = r.ok ? Number(String(r.stdout).trim()) : NaN;
557
+ return Number.isFinite(n) && n > 0 ? n * 1000 : null;
558
+ };
559
+ if (sha) {
560
+ const local = git(['cat-file', '-e', `${sha}^{commit}`], repo);
561
+ if (local.ok) return at(sha);
562
+ }
563
+ const f = git(['fetch', '--quiet', '--no-tags', remote, ref], repo, { timeoutMs: 60_000 });
564
+ if (!f.ok) return null;
565
+ return at('FETCH_HEAD');
566
+ }
567
+
546
568
  /** List worktree paths registered in a repo (porcelain). */
547
569
  function worktreeList(repo) {
548
570
  const r = git(['worktree', 'list', '--porcelain'], repo);
@@ -1859,7 +1881,7 @@ module.exports = {
1859
1881
  detectTrunk, branchExists, branchRefs, existingBranchRef,
1860
1882
  claimRemote, remoteHeads, parseRemoteHeads, CLAIM_REF_PREFIX, claimRef, pushClaimRef, deleteClaimRef,
1861
1883
  CLAIM_LOCK_PREFIX, claimLockRef, parseClaimLocks, claimLockMessage, parseClaimLockMessage, makeClaimLockCommit,
1862
- takeClaimLocks, releaseClaimLock, readClaimLock,
1884
+ takeClaimLocks, releaseClaimLock, readClaimLock, remoteRefCommitTime,
1863
1885
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1864
1886
  dirtyTracked, dirtyUntracked, dirtyAny,
1865
1887
  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 };