@futurelastic/colab-handbook 1.13.0-rc.44 → 1.13.0-rc.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.13.0-rc.44"
36
+ "version": "1.13.0-rc.46"
37
37
  }
package/tools/colab CHANGED
@@ -78,6 +78,7 @@ const releaseFinalize = require('./lib/release-finalize');
78
78
  const releaseChannel = require('./lib/release-channel');
79
79
  const shippedBranch = require('./lib/shipped-branch');
80
80
  const shipRoles = require('./lib/ship-roles'); // #372
81
+ const shipHandoff = require('./lib/ship-handoff'); // #578
81
82
  const refsBrake = require('./lib/refs-brake'); // #385
82
83
  const localAdopt = require('./lib/local-adopt'); // #393
83
84
  const ownerBranch = require('./lib/owner-branch'); // #394
@@ -10275,7 +10276,7 @@ function ciCureTrailerLine(cureVerdict, branch, trunk) {
10275
10276
  return `CI-Cure: branch ${branch} over-red ${trunk}@${shortSha(cureVerdict.redSha)} evidence ${shortSha(cureVerdict.evidenceSha)}${via}${admittedSuffix}${progressSuffix}`;
10276
10277
  }
10277
10278
 
10278
- const HELP_SHIP = `colab ship [--repo <path>] [--worktree <name> | --branch <br> | --direct] [--message "<msg>"] [--refs <N[,M]>] [--keep-worktree] [--delete-branch | --keep-branch] [--adopt] [--answered-by <name>] [--session <id>] [--session-name <s>] [--dry] [--json]
10279
+ const HELP_SHIP = `colab ship [--repo <path>] [--worktree <name> | --branch <br> | --direct] [--message "<msg>"] [--refs <N[,M]>] [--keep-worktree] [--delete-branch | --keep-branch] [--adopt | --handoff <comment-url>] [--answered-by <name>] [--session <id>] [--session-name <s>] [--dry] [--json]
10279
10280
  colab ship --batch <b1,b2[,b3]> [--repo <path>] [--keep-worktree] [--delete-branch | --keep-branch] [--session <id>] [--session-name <s>] [--dry]
10280
10281
 
10281
10282
  The ONE sanctioned door for code-wrap Phase B: squash-merge a session branch into the BASE IT WAS
@@ -10371,6 +10372,26 @@ here, or pass --adopt if it genuinely has no issue — the squash then carries a
10371
10372
  \`Colab-Adopted: origin/<br> @ <sha> on <host> (machine <id>)\` trailer. A LOCAL no-digit branch is
10372
10373
  still a legitimate zero. --adopt never bypasses a branch that names issues.
10373
10374
 
10375
+ A HAND-OFF (#578) is the non-force door for a branch whose claim lives on ANOTHER machine:
10376
+ \`colab ship --branch <br> --handoff <url>\`, where <url> is the executor's hand-off comment
10377
+ (…/issues/<N>#issuecomment-<id>). With zero claims here, ship takes the issue set from the branch
10378
+ name's trailing run once the hand-off proves all of: the comment is on one of THIS repo's issues,
10379
+ one the branch carries; it names the branch and a sha that is the remote branch's CURRENT head (a
10380
+ branch that moved after its hand-off needs a new one — except by base-sync merges, #579, below); and every issue the branch carries has a
10381
+ live \`🔒 Claimed\` comment on that branch, posted by the hand-off's author before it. Nothing is
10382
+ claimed or taken over here: the executor keeps its claim, worktree and branch until it confirms
10383
+ the land, the shipped branch is kept, the squash carries \`Colab-Handoff: <url> @ <sha>\`, and each
10384
+ 🚢 comment names the hand-off. Any check failing refuses (exit 1); --force is never involved, and
10385
+ the human takeover (\`colab claim --force\`) stays the only other way in. Not with --adopt,
10386
+ --batch or --direct, and not when this machine already holds a claim on the branch.
10387
+
10388
+ A remote-built branch that fell BEHIND its base (#579) is synced by the lander as usual (B0: merge
10389
+ the base in, push) — and the hand-off still verifies, because the commits between the handed-off
10390
+ sha and the new head are each a PURE base-sync merge: two parents, the second already on the base,
10391
+ and a tree equal to git's own conflict-free merge of the two. A fix-up, a rebase, or a merge whose
10392
+ conflict was resolved by hand is not one, and still needs a new hand-off from the executor. The
10393
+ trailer then reads \`Colab-Handoff: <url> @ <handed-off sha> (synced to <head> by N base merge(s))\`.
10394
+
10374
10395
  UNATTACHED CLAIMS (#319). A claim taken with no --worktree and no --branch (\`colab claim <N>
10375
10396
  --session <id>\`) is carried by a branch ship only when BOTH hold: its session equals this ship's
10376
10397
  (--session / COLAB_SESSION, or the worktree record's), and the branch name's trailing group names
@@ -11897,8 +11918,13 @@ function cmdShipDryJson(opts) {
11897
11918
  const trunk = resolveTrunk(repoAbs, doc);
11898
11919
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
11899
11920
  if (sess.branch === trunk) throw new UserError(`Refusing: --branch is the trunk itself (${trunk}) — nothing to ship. A unit committed straight to ${trunk} closes with \`colab ship --direct\` (#302)`);
11921
+ const handoff = applyShipHandoff(repoAbs, sess, opts, trunk); // #578 — same resolution as the prose path
11900
11922
 
11901
11923
  const checks = [];
11924
+ if (handoff) {
11925
+ checks.push({ name: 'hand-off verified (#578)', ok: handoff.ok, class: handoff.ok ? null : HUMAN_GATED,
11926
+ detail: handoff.ok ? handoffDetail(handoff) : `${handoff.reason}: ${handoff.detail}` });
11927
+ }
11902
11928
  let target = null;
11903
11929
  // #74/#263: the close-gate split (closeIssues/refsIssues/checklistFindings) is reported
11904
11930
  // ALONGSIDE `checks` AS WELL AS folded into it — `closeIssues`/`refsIssues`/`checklistFindings`
@@ -12968,6 +12994,72 @@ function autonomyGatePayload(gate) {
12968
12994
  }
12969
12995
 
12970
12996
  /** The sha a branch name resolves to, local first, else origin's copy (#324's remote-only shape). */
12997
+ /**
12998
+ * #578 — `--handoff <comment-url>`: verify the executor's recorded hand-off and, when it holds, take
12999
+ * the session's issue set from it (tools/lib/ship-handoff.js says what it must prove). Returns null
13000
+ * without --handoff, the failing verdict on a refusal, the passing one after mutating `sess`.
13001
+ *
13002
+ * Writes nothing locally: no claim record, no worktree record. The executor's claim is the claim;
13003
+ * this ship only lands what it handed off, so B3 has nothing of THIS machine's to release.
13004
+ */
13005
+ function applyShipHandoff(repoAbs, sess, opts, trunk) {
13006
+ if (!opts.handoff) return null;
13007
+ if (opts.adopt) throw new UserError('--handoff and --adopt contradict each other: --adopt is for a branch with NO issue, --handoff for one whose claim lives on another machine — drop --adopt');
13008
+ if (sess.issues.length) {
13009
+ throw new UserError(`--handoff is the door for a branch with NO claim on this machine, and this machine holds ${sess.issues.map((n) => '#' + n).join(' ')} ` +
13010
+ `for ${sess.branch} — ship it without --handoff`);
13011
+ }
13012
+ const u = shipHandoff.parseHandoffUrl(opts.handoff);
13013
+ let comment = null;
13014
+ if (u) {
13015
+ const r = git.ghApi(repoAbs, [`repos/{owner}/{repo}/issues/comments/${u.commentId}`]);
13016
+ if (r.ok) {
13017
+ try {
13018
+ const j = JSON.parse(r.stdout);
13019
+ comment = { body: j.body || '', login: (j.user && j.user.login) || '', createdAt: j.created_at || '', htmlUrl: j.html_url || '' };
13020
+ } catch (_) { comment = null; }
13021
+ }
13022
+ }
13023
+ // The head check must read the remote as it is NOW, not a tracking ref from whenever this clone last fetched.
13024
+ const remote = git.remoteFor(repoAbs);
13025
+ if (u && comment) git.git(['fetch', '--quiet', remote, `+refs/heads/${sess.branch}:refs/remotes/${remote}/${sess.branch}`], repoAbs);
13026
+ const refs = git.branchRefs(repoAbs, sess.branch, remote);
13027
+ // #579: base-sync merges the lander (B0) stacked on the handed-off head do not void the hand-off.
13028
+ // Read against the base as it is NOW — the merges' second parents must already be on it.
13029
+ let syncChain = [];
13030
+ if (u && comment && refs && refs.remoteSha && trunk) {
13031
+ git.git(['fetch', '--quiet', remote, `+refs/heads/${trunk}:refs/remotes/${remote}/${trunk}`], repoAbs);
13032
+ syncChain = shipHandoff.syncMergeChain((a) => git.git(a, repoAbs), refs.remoteSha, `refs/remotes/${remote}/${trunk}`);
13033
+ }
13034
+ const claimsByIssue = {};
13035
+ if (u && comment) {
13036
+ for (const n of shipguard.branchIssueNumbers(sess.branch)) {
13037
+ const info = git.ghIssueView(repoAbs, n, ['comments']);
13038
+ claimsByIssue[n] = info ? liveClaimComments(info.comments || []).map((c) => ({ ...c })) : null;
13039
+ }
13040
+ }
13041
+ const v = shipHandoff.handoffVerdict({ url: opts.handoff, comment, branch: sess.branch, refs, claimsByIssue, syncChain });
13042
+ if (!v.ok) return v;
13043
+ sess.issues = v.issues;
13044
+ sess.handoff = v;
13045
+ // #372: the implementer is the executor that handed off — name it, never leave it reading as the shipper.
13046
+ const ex = (claimsByIssue[v.issues[0]] || []).find((c) => c.branch === sess.branch && c.login === v.executor.login);
13047
+ if (ex && (ex.session || ex.sessionName)) sess.holder = { session: ex.session || '', sessionName: ex.sessionName || '' };
13048
+ return v;
13049
+ }
13050
+
13051
+ function handoffDetail(v) {
13052
+ const head = v.syncMerges
13053
+ ? `${shortSha(v.handedOff)}, under ${v.syncMerges} clean base-sync merge${v.syncMerges === 1 ? '' : 's'} to the remote head ${shortSha(v.sha)} (#579)`
13054
+ : `${shortSha(v.sha)} = the remote head`;
13055
+ return `${v.url} hands off ${head}; executor ${v.executor.login}'s live claim on ${v.issues.map((n) => '#' + n).join(' ')}`;
13056
+ }
13057
+
13058
+ /** The clause the 🚢 comment carries for a hand-off land — the executor still holds its claim. */
13059
+ function handoffEvidence(v) {
13060
+ return v ? ` · landed from the executor's hand-off ${v.url} — its claim and worktree stay until it confirms the land` : '';
13061
+ }
13062
+
12971
13063
  function shipRefFor(repoAbs, branch) {
12972
13064
  const r = git.branchRefs(repoAbs, branch);
12973
13065
  return r.localSha || r.remoteSha || branch;
@@ -12975,7 +13067,7 @@ function shipRefFor(repoAbs, branch) {
12975
13067
 
12976
13068
  function cmdShip(argv) {
12977
13069
  const opts = parseArgs(argv, {
12978
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch', '--answered-by': 'answeredBy' },
13070
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch', '--answered-by': 'answeredBy', '--handoff': 'handoff' },
12979
13071
  // #479: a repeated --refs used to keep only its LAST value, and every dropped issue then became a
12980
13072
  // `Closes` line on trunk — an issue meant to stay open, auto-closed by the push. --refs now
12981
13073
  // accumulates (a repeat is the same as one comma list); every OTHER value flag to ship refuses a
@@ -12990,6 +13082,8 @@ function cmdShip(argv) {
12990
13082
  // — refuse the combination rather than silently ignore --json on a real ship.
12991
13083
  if (opts.json && !opts.dry) throw new UserError('--json currently only applies together with --dry — see `colab ship --help`');
12992
13084
  if (shippedBranch.conflictingFlags(opts)) throw new UserError('--delete-branch and --keep-branch contradict each other — pass one (see `colab ship --help`, #368)');
13085
+ // #578: a hand-off names ONE branch; batch and trunk-direct have no single branch for it to name.
13086
+ if (opts.handoff && (opts.batch || opts.direct)) throw new UserError(`--handoff applies to one --branch ship — not to ${opts.batch ? '--batch' : '--direct'} (see \`colab ship --help\`)`);
12993
13087
  if (opts.batch) return cmdShipBatch(opts); // #373 — its own re-entrant path; nothing below changes
12994
13088
  // A fully separate code path, deliberately: the prose/table path below is unchanged by this
12995
13089
  // feature (CONVENTIONS/#77 requires it stay byte-identical), so --dry --json does its own
@@ -13007,6 +13101,17 @@ function cmdShip(argv) {
13007
13101
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
13008
13102
  if (sess.branch === trunk) throw new UserError(`Refusing: --branch is the trunk itself (${trunk}) — nothing to ship. A unit committed straight to ${trunk} closes with \`colab ship --direct\` (#302)`);
13009
13103
 
13104
+ // #578: a remote-built branch's issue set, from its executor's recorded hand-off. Before the
13105
+ // branch-resolves check below: reading the hand-off fetches the branch, which is what makes a
13106
+ // remote-only branch resolve here at all.
13107
+ const handoff = applyShipHandoff(repoAbs, sess, opts, trunk);
13108
+ if (handoff && !handoff.ok) {
13109
+ process.stderr.write(`✗ Refusing --handoff: ${handoff.detail}. Re-run with --handoff <a hand-off naming ${sess.branch} and its current head>, ` +
13110
+ `ship from the executor's machine, or a human takes the claim over (\`colab claim <N> --branch ${sess.branch} --force\`, a human act).\n`);
13111
+ process.stderr.write(' Nothing was claimed or taken over here — the executor\'s claim still stands.\n');
13112
+ return 1;
13113
+ }
13114
+
13010
13115
  // ---- the recorded branch must RESOLVE, before anything else is computed ----
13011
13116
  // Everything downstream is keyed to this name: the claim lookup above, the migration diff, the
13012
13117
  // squash. A worktree record holding a role word or a deleted branch fails all three quietly —
@@ -13066,6 +13171,7 @@ function cmdShip(argv) {
13066
13171
  const gh = isGhUsable(repoAbs);
13067
13172
  // #345: the gate that passed is the table's first row, so a reader sees WHICH door opened it.
13068
13173
  const checks = [['✓', 'autonomy granted', autonomyGate.detail]];
13174
+ if (handoff) checks.push(['✓', 'hand-off verified (#578)', handoffDetail(handoff)]);
13069
13175
 
13070
13176
  // Which claimed issues are REFERENCED (Refs #N), not closed — three sources unioned by
13071
13177
  // resolveCloseRefsSplit (#48, #74): --refs, the tracking label, and #74's close gate (an
@@ -13738,7 +13844,7 @@ function cmdShip(argv) {
13738
13844
  (publicOmit ? (m) => print(` ${m}`) : warn)(`Machine trailer ${machineTrailerSummary(trailerDecision)}`);
13739
13845
  }
13740
13846
  const machineLine = trailerDecision.line;
13741
- const ciTrailerLines = [ciTrailer, adoptTrailer, machineLine].filter(Boolean);
13847
+ const ciTrailerLines = [ciTrailer, adoptTrailer, shipHandoff.handoffTrailer(sess.handoff), machineLine].filter(Boolean);
13742
13848
  if (opts.message) {
13743
13849
  // --message overrides the subject/body, but Closes is spliced in as its own paragraph — never
13744
13850
  // concatenated. Appending it welded ` — Closes #N` onto whatever the message ended with, which
@@ -13747,7 +13853,7 @@ function cmdShip(argv) {
13747
13853
  for (const tl of ciTrailerLines) {
13748
13854
  if (commitMsg.toLowerCase().includes(tl.toLowerCase())) continue;
13749
13855
  const lastLine = commitMsg.split('\n').pop().trim();
13750
- commitMsg += (/^(?:Co-authored-by|Signed-off-by|Claude-Session|Reviewed-by|CI-Grant|CI-Cure|Colab-Adopted|Machine):\s*\S/i.test(lastLine) ? '\n' : '\n\n') + tl;
13856
+ commitMsg += (/^(?:Co-authored-by|Signed-off-by|Claude-Session|Reviewed-by|CI-Grant|CI-Cure|Colab-Adopted|Colab-Handoff|Machine):\s*\S/i.test(lastLine) ? '\n' : '\n\n') + tl;
13751
13857
  }
13752
13858
  } else {
13753
13859
  // Preserve the branch's crafted commit (subject + footers); insert Closes/Refs above the footers.
@@ -13957,7 +14063,7 @@ function cmdShip(argv) {
13957
14063
  pushEvent('ship', {
13958
14064
  repo: repoAbs, worktree: sess.name, session: sess.session,
13959
14065
  issue: sess.issues.length === 1 ? sess.issues[0] : undefined,
13960
- payload: { state: 'merged', branch: sess.branch, target, sha, issues: sess.issues, ...(adoptInfo ? { adopted: adoptInfo } : {}) },
14066
+ payload: { state: 'merged', branch: sess.branch, target, sha, issues: sess.issues, ...(adoptInfo ? { adopted: adoptInfo } : {}), ...(sess.handoff ? { handoff: { url: sess.handoff.url, sha: sess.handoff.sha } } : {}) },
13961
14067
  });
13962
14068
 
13963
14069
  // Then, PER ISSUE, a merge-completion event (#46 §2, following #45 §2). The ship event above is
@@ -13979,11 +14085,12 @@ function cmdShip(argv) {
13979
14085
  // window itself now OPENS at the push (e2, #304), not here: post-ship's warnings belong in the
13980
14086
  // same block, and re-assigning the collector here would silently discard them.
13981
14087
  shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts,
13982
- evidenceExtra: opts.humanDoorEvidence || '' }); // #525
14088
+ evidenceExtra: (opts.humanDoorEvidence || '') + handoffEvidence(sess.handoff) }); // #525, #578
13983
14089
 
13984
14090
  print('');
13985
14091
  print(`✓ Shipped ${sess.branch} → ${target} @ ${sha}${sess.issues.length ? ' (' + sess.issues.map((n) => '#' + n).join(' ') + ')' : ''}`);
13986
14092
  if (adoptInfo) print(` adopted from ${adoptInfo.remote || 'origin'}/${adoptInfo.branch} @ ${shortSha(adoptInfo.remoteSha)} — recorded in the Colab-Adopted: trailer (#324)`);
14093
+ if (sess.handoff) print(` landed from the hand-off ${sess.handoff.url} — the executor's claim and worktree stay until it confirms the land (#578)`);
13987
14094
  if (target !== trunk) print(` "${target}" is a declared line: this work is NOT in ${trunk} until a human merges the line.`);
13988
14095
  // #114: everything deferred since the push (e2, #304) lands here, AFTER the success line — not scattered above it
13989
14096
  // where a long ship scrolls it out of view. The merge itself already landed either way; this is
@@ -14025,7 +14132,8 @@ function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, re
14025
14132
  // B3 (cont.) — the shipped branch. Kept by default; --delete-branch opts in. MUST come after the
14026
14133
  // worktree removal above: git refuses to delete a branch checked out in a worktree.
14027
14134
  // #368: a Refs-only ship deletes unless --keep-branch — see tools/lib/shipped-branch.js.
14028
- const disposition = shippedBranch.shippedBranchDisposition({ closeIssues, refsIssues, deleteBranch: opts.deleteBranch, keepBranch: opts.keepBranch });
14135
+ // #578: a handed-off branch is the executor's until it confirms the land — never deleted for it.
14136
+ const disposition = shippedBranch.shippedBranchDisposition({ closeIssues, refsIssues, deleteBranch: opts.deleteBranch, keepBranch: opts.keepBranch || (!!sess.handoff && !opts.deleteBranch) });
14029
14137
  handleShippedBranch(repoAbs, target, sess.branch, { disposition, worktreeKept, integration });
14030
14138
 
14031
14139
  // ---- (g/h) B4 verify + post summary per issue ----
@@ -55,7 +55,7 @@ function releaseComments(sorted) {
55
55
 
56
56
  /**
57
57
  * Live claim comments on an issue. Returns [{login, host, machine, session, sessionName, at,
58
- * identity}], `at` = the comment's real GitHub createdAt (authoritative, sub-second). `identity`
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.
61
61
  *
@@ -91,7 +91,8 @@ function liveClaimComments(comments, comps) {
91
91
  const { host, session, sessionName } = claim;
92
92
  const machineTok = claim.machine; // #327 — '' on a legacy comment: compared by host
93
93
  const at = c.createdAt;
94
- const entry = { login, host, machine: machineTok, session, sessionName, at };
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
96
  const cancelled = releases.some((r) => r.at > at && (r.kind === 'release'
96
97
  || (r.login === login && !isNamedWinner(entry, r.winner))));
97
98
  if (!cancelled) live.push({ ...entry, identity: claimIdentity.identityString({ login, host, session }, comps) });
@@ -0,0 +1,174 @@
1
+ 'use strict';
2
+ /**
3
+ * #578 — `colab ship --branch <br> --handoff <comment-url>`: land a branch whose claim lives on
4
+ * ANOTHER machine, from the hand-off its executor already recorded, without `--force`.
5
+ *
6
+ * The problem. `colab ship` takes the issue set to close from THIS machine's claim registry only.
7
+ * A branch built and wrapped on machine A and landed from machine B has its claim in A's registry,
8
+ * so on B ship reads zero claims and refuses (#153 / #324). The only way to write a record on B was
9
+ * `colab claim --force` — a human-only takeover — so an agent lander had no sanctioned path, and
10
+ * every remote-built branch waited for a person even when it had passed review and merged clean.
11
+ *
12
+ * The door. The executor has already said, on the tracker, which branch it handed off and at which
13
+ * head. That comment, checked against git and against the executor's own live claim, is the
14
+ * evidence ship would otherwise get from a local claim. Nothing on B's registry is written and
15
+ * nothing of A's is taken over: A keeps its claim, worktree and branch until it confirms the land
16
+ * (its own `colab worktree rm`, which releases the claim as usual).
17
+ *
18
+ * What a hand-off must prove, in order — the first failure is the verdict:
19
+ * 1. the URL is an issue-comment URL (`…/issues/<N>#issuecomment-<id>`);
20
+ * 2. the comment was read from THIS repo (fetched through `{owner}/{repo}`, so an off-repo id is a
21
+ * 404) and its own html_url names the same issue the URL does;
22
+ * 3. that issue is one the branch NAME carries (its trailing number run, CONVENTIONS.md §4) — the
23
+ * issue set is exactly that run, so git corroborates every `Closes #N` (#87) by construction;
24
+ * 4. the body names the branch, as a whole token;
25
+ * 5. the branch exists on the remote, and this machine holds no diverging copy of its own;
26
+ * 6. the body names a sha that is a prefix of the remote branch's CURRENT head — a branch that
27
+ * moved after its hand-off was not handed off at that head, and lands only after a new one.
28
+ * ONE movement is not "moved" (#579): base-sync merges stacked on the handed-off head. The
29
+ * stale-base gate (#395) sends every behind-trunk branch through B0's sync, and the sync moves
30
+ * the head; without this a remote-built branch that fell behind could land only after its
31
+ * executor — whose session has usually ended — posted again. A sync merge is accepted only
32
+ * when it adds nothing of its own (syncMergeChain, below): two parents, the second already on
33
+ * the base, and a tree equal to git's own clean merge of the two. Any other commit after the
34
+ * handed-off sha — a fix-up, a rebase, a hand-resolved conflict — is still `head-moved`;
35
+ * 7. every issue the branch carries has a LIVE `🔒 Claimed` comment naming this branch, posted by
36
+ * the hand-off's author before the hand-off — the claim really does live elsewhere, and the
37
+ * party handing off is the party holding it.
38
+ *
39
+ * Pure: every input is already read. tools/colab does the IO (`gh api`, `git fetch`, issue views).
40
+ */
41
+
42
+ const { branchIssueNumbers } = require('./branch-name');
43
+
44
+ /** `https://github.com/<o>/<r>/issues/<N>#issuecomment-<id>` → parts, or null. Host-agnostic (GHE). */
45
+ function parseHandoffUrl(url) {
46
+ const m = String(url || '').trim().match(/^https?:\/\/[^/\s]+\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)\/?#issuecomment-(\d+)$/);
47
+ if (!m) return null;
48
+ return { owner: m[1], repo: m[2], issue: Number(m[3]), commentId: m[4] };
49
+ }
50
+
51
+ function escapeRe(s) { return String(s).replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); }
52
+
53
+ /** Does `body` name `branch` as a whole token (not as a prefix of a longer branch name)? */
54
+ function namesBranch(body, branch) {
55
+ if (!branch) return false;
56
+ return new RegExp(`(^|[^A-Za-z0-9._/-])${escapeRe(branch)}(?![A-Za-z0-9._/-])`).test(String(body || ''));
57
+ }
58
+
59
+ /** Every 7–40 hex token in `body`, lower-cased — the candidate head shas a hand-off names. */
60
+ function namedShas(body) {
61
+ return [...String(body || '').matchAll(/(?<![0-9A-Za-z])([0-9a-fA-F]{7,40})(?![0-9A-Za-z])/g)]
62
+ .map((m) => m[1].toLowerCase());
63
+ }
64
+
65
+ /**
66
+ * The verdict. Inputs:
67
+ * url — the --handoff value
68
+ * comment — { body, login, createdAt, htmlUrl } as read from THIS repo, or null (unreadable)
69
+ * branch — the branch being shipped
70
+ * refs — git.branchRefs(): { localSha, remoteSha, localFromRemote }
71
+ * claimsByIssue — { [n]: [{ login, branch, at, host, machine }] } live claim comments per issue,
72
+ * or null for an issue whose comments could not be read
73
+ * syncChain — (#579) the first-parent ancestors of the remote head reached through pure
74
+ * base-sync merges only, nearest first (syncMergeChain's output); [] or absent = none
75
+ * Returns { ok: true, issues, sha, handedOff, syncMerges, executor, url } or { ok: false, reason, detail }.
76
+ * `sha` is what lands (the remote head); `handedOff` is the sha the hand-off named — equal to `sha`
77
+ * unless the head was synced, in which case `syncMerges` counts the merges between them.
78
+ */
79
+ function handoffVerdict({ url, comment, branch, refs, claimsByIssue, syncChain }) {
80
+ const no = (reason, detail) => ({ ok: false, reason, detail });
81
+ const u = parseHandoffUrl(url);
82
+ if (!u) return no('bad-url', `--handoff ${url || '(empty)'} is not an issue-comment URL (…/issues/<N>#issuecomment-<id>)`);
83
+ if (!comment) return no('unreadable', `comment ${u.commentId} could not be read from this repo — it must be a comment on one of this repo's issues`);
84
+ const got = parseHandoffUrl(comment.htmlUrl);
85
+ if (!got || got.commentId !== u.commentId || got.issue !== u.issue ||
86
+ got.owner.toLowerCase() !== u.owner.toLowerCase() || got.repo.toLowerCase() !== u.repo.toLowerCase()) {
87
+ return no('mismatch', `the URL says ${u.owner}/${u.repo}#${u.issue}, but comment ${u.commentId} is ${comment.htmlUrl || 'somewhere else'}`);
88
+ }
89
+ const issues = branchIssueNumbers(branch);
90
+ if (!issues.length) return no('branch-names-no-issue', `${branch} carries no trailing issue number, so a hand-off has no issue set to close — ship it with --adopt if it genuinely has none`);
91
+ if (!issues.includes(u.issue)) return no('not-this-branch', `the hand-off is on #${u.issue}, which ${branch} does not carry (${issues.map((n) => '#' + n).join(' ')})`);
92
+ if (!namesBranch(comment.body, branch)) return no('branch-not-named', `the hand-off comment does not name the branch ${branch}`);
93
+ if (!refs || !refs.remoteSha) return no('no-remote-branch', `${branch} is not on the remote — a hand-off lands a pushed branch only`);
94
+ // Ship merges the local ref when one exists (shipRefFor), so it must BE the remote head: a stale
95
+ // copy a DWIM checkout made earlier would land a sha the hand-off never named.
96
+ if (refs.localSha && refs.localSha !== refs.remoteSha) {
97
+ return no('local-diverges', refs.localFromRemote
98
+ ? `this machine's ${branch} (${refs.localSha.slice(0, 8)}, created from the remote by an earlier checkout) is behind or apart from the remote's (${refs.remoteSha.slice(0, 8)}) — reset it to the remote's (git branch -f ${branch} <remote>/${branch}, from a checkout not on it) and re-run`
99
+ : `this machine has its own ${branch} (${refs.localSha.slice(0, 8)}) that differs from the remote's (${refs.remoteSha.slice(0, 8)}) — not a remote-built branch here`);
100
+ }
101
+ const head = String(refs.remoteSha).toLowerCase();
102
+ const shas = namedShas(comment.body);
103
+ // #579: the head itself first, then each sha a pure base-sync merge sits on, nearest first.
104
+ const lineage = [head, ...(Array.isArray(syncChain) ? syncChain : []).map((x) => String(x).toLowerCase())];
105
+ const at = lineage.findIndex((l) => shas.some((s) => l.startsWith(s)));
106
+ if (at < 0) {
107
+ const synced = lineage.length > 1 ? ` (nor ${lineage.length - 1 === 1 ? 'the sha' : 'any of the ' + (lineage.length - 1) + ' shas'} its base-sync merges sit on)` : '';
108
+ return no('head-moved', shas.length
109
+ ? `the hand-off names ${shas.map((s) => s.slice(0, 8)).join(', ')}, but the remote ${branch} is at ${head.slice(0, 8)}${synced} — the branch moved after it was handed off by more than a clean merge of its base; ask its executor for a new hand-off`
110
+ : `the hand-off names no head sha — it must say which commit it hands off (the remote is at ${head.slice(0, 8)})`);
111
+ }
112
+ let executor = null;
113
+ for (const n of issues) {
114
+ const live = claimsByIssue ? claimsByIssue[n] : null;
115
+ if (!live) return no('claims-unreadable', `#${n}'s comments could not be read — the executor's claim cannot be checked`);
116
+ const match = live.find((c) => c.branch === branch && c.login === comment.login && c.at < comment.createdAt);
117
+ if (!match) {
118
+ return no('no-executor-claim', `#${n} has no live 🔒 claim on ${branch} by ${comment.login || 'the hand-off author'} posted before the hand-off — ` +
119
+ 'the hand-off must come from the party holding the claim');
120
+ }
121
+ if (!executor) executor = { login: match.login, host: match.host, machine: match.machine || '' };
122
+ }
123
+ return { ok: true, issues, sha: refs.remoteSha, handedOff: lineage[at], syncMerges: at, executor, url: String(url).trim() };
124
+ }
125
+
126
+ /**
127
+ * The squash trailer recording the door the issue set came through. It names the HANDED-OFF sha —
128
+ * the one the executor vouched for — and, after a sync (#579), the head that actually landed.
129
+ */
130
+ function handoffTrailer(v) {
131
+ if (!v || !v.ok) return '';
132
+ const handed = String(v.handedOff || v.sha).slice(0, 12);
133
+ const synced = v.syncMerges ? ` (synced to ${String(v.sha).slice(0, 12)} by ${v.syncMerges} base merge${v.syncMerges === 1 ? '' : 's'})` : '';
134
+ return `Colab-Handoff: ${v.url} @ ${handed}${synced}`;
135
+ }
136
+
137
+ /**
138
+ * #579 — walk the remote head's first-parent line while each commit is a PURE base-sync merge, and
139
+ * return the shas it sits on, nearest first. A commit qualifies only when all three hold:
140
+ * - exactly two parents (a squash, a rebase, a cherry-pick or a fix-up has one);
141
+ * - its second parent is already on the base (`merge-base --is-ancestor p2 <baseRef>`) — it
142
+ * brought in landed base content, not a side branch;
143
+ * - its tree equals `git merge-tree --write-tree p1 p2`'s — git's own conflict-free merge of the
144
+ * two. A conflict (exit 1) or a hand-edited result (a different tree) is NOT pure: someone wrote
145
+ * content into it, and only the executor can vouch for content.
146
+ * The walk stops at the first commit that fails, so a sync merge stacked on a fix-up yields only
147
+ * the fix-up's sha — which a hand-off naming the commit before the fix-up does not match.
148
+ *
149
+ * `run(args)` is git in the repo, returning { ok, code, stdout } (tools/lib/git.js `git`). A git
150
+ * too old for `merge-tree --write-tree` (< 2.38) proves nothing, so the chain is just empty there:
151
+ * the hand-off then needs the exact head, exactly as before #579.
152
+ */
153
+ function syncMergeChain(run, head, baseRef, maxDepth = 50) {
154
+ const chain = [];
155
+ let cur = String(head || '');
156
+ for (let i = 0; cur && i < maxDepth; i++) {
157
+ const p = run(['rev-list', '--parents', '-n', '1', cur]);
158
+ if (!p.ok) break;
159
+ const parts = String(p.stdout).trim().split(/\s+/);
160
+ if (parts.length !== 3) break;
161
+ const [, p1, p2] = parts;
162
+ if (run(['merge-base', '--is-ancestor', p2, baseRef]).code !== 0) break;
163
+ const mt = run(['merge-tree', '--write-tree', p1, p2]);
164
+ if (mt.code !== 0) break;
165
+ const merged = String(mt.stdout).split('\n')[0].trim();
166
+ const tree = run(['rev-parse', `${cur}^{tree}`]);
167
+ if (!tree.ok || !/^[0-9a-f]{40,64}$/.test(merged) || merged !== String(tree.stdout).trim()) break;
168
+ chain.push(p1.toLowerCase());
169
+ cur = p1;
170
+ }
171
+ return chain;
172
+ }
173
+
174
+ module.exports = { parseHandoffUrl, namesBranch, namedShas, handoffVerdict, handoffTrailer, syncMergeChain };