@futurelastic/colab-handbook 1.14.0-rc.6 → 1.14.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/audit/audit.mjs CHANGED
@@ -1422,11 +1422,11 @@ function auditRepoInner(target, ctx) {
1422
1422
  {
1423
1423
  const pol = migrationGrant.parseGrantPolicy(cfg);
1424
1424
  info.migrationGrant = pol.policy;
1425
- // #596: an undeclared key is no longer "human, full stop" — the owner-level value (a tracker
1426
- // record, `colab owner-policy show`) may apply, and this offline audit cannot read it. So the
1425
+ // #598: an undeclared key is not "human, full stop" — the machine-level value (the gating
1426
+ // machine's colab config) may apply, and this audit cannot know which machine gates. So the
1427
1427
  // source is reported: `repo` (declared here, final) or `undeclared` (repo-local default human,
1428
- // owner level unread). The round-trip warning below stays on a DECLARED reviewer only: for an
1429
- // owner-level reviewer the mint itself refuses without the job, which is where it surfaces.
1428
+ // machine level unread). The round-trip warning below stays on a DECLARED reviewer only: for a
1429
+ // machine-level reviewer the mint itself refuses without the job, which is where it surfaces.
1430
1430
  info.migrationGrantSource = pol.declared ? "repo" : "undeclared";
1431
1431
  if (!pol.valid) fail(pol.reason);
1432
1432
  // #494: R needs a live `Migration round-trip…` job. Without one every reviewer grant fails R
package/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.14.0-rc.6"
36
+ "version": "1.14.0-rc.8"
37
37
  }
package/tools/colab CHANGED
@@ -44,6 +44,7 @@ const blockedBy = require('./lib/blocked-by');
44
44
  const ciGrant = require('./lib/ci-grant');
45
45
  const trustHumans = require('./lib/trust-humans');
46
46
  const ownerPolicy = require('./lib/owner-policy');
47
+ const grantPolicy = require('./lib/grant-policy');
47
48
  const ciCure = require('./lib/ci-cure');
48
49
  const ciVerdict = require('./lib/ci-verdict');
49
50
  const baseCiVerdict = require('./lib/base-ci-verdict');
@@ -3851,8 +3852,8 @@ It is minted only when ALL of these hold, checked before any network call:
3851
3852
  - the record is well-formed AND passing (approve · checklist pass · escalation clear · CI pass) —
3852
3853
  a grant carrying a failing review is a contradiction, so it is refused, not recorded;
3853
3854
  - the branch is pushed, and --head (if given) equals origin's tip — the grant binds that tip;
3854
- - the policy resolves to \`reviewer\` (#596): this checkout's project.yml \`migration-grant:\` when
3855
- declared (#398), else the owner-level value (\`colab owner-policy\`), else human;
3855
+ - the policy resolves to \`reviewer\` (#598): this checkout's project.yml \`migration-grant:\` when
3856
+ declared (#398), else this machine's value (\`colab config set migration-grant\`), else human;
3856
3857
  - checklist-items, when given, is <passed>/${migrationGrant.REVIEW_CHECKLIST_ITEMS} and, with checklist pass, every item
3857
3858
  passed (#457) — the record counts against the checklist the migration-review skill walks today.
3858
3859
  Then, read from CI after the tracker read and before anything is written (#457):
@@ -3861,7 +3862,7 @@ Then, read from CI after the tracker read and before anything is written (#457):
3861
3862
  head and carries the job. A repo whose CI has no such job cannot mint a reviewer grant at all.
3862
3863
  COLAB_HUMAN=1 is still required for every role. The reviewer identity is DECLARED, not attested.
3863
3864
  \`colab ship\` honours a reviewer grant only when ALL of (#401): P the policy at the target resolves to
3864
- reviewer (its project.yml key, else the owner-level value, else human — #596) · M this record is live, trusted and passing · HEAD its head is the
3865
+ reviewer (its project.yml key, else this machine's value, else human — #598) · M this record is live, trusted and passing · HEAD its head is the
3865
3866
  branch's exact remote head, or its \`migrations\` id equals the id at that head · R the live
3866
3867
  "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job passed on the SHIPPED head (re-read by ship, never
3867
3868
  taken from the record). Any condition failing → a human runs Phase B.
@@ -3966,17 +3967,15 @@ function migrationGrantReviewRecord(repoAbs, opts) {
3966
3967
 
3967
3968
  // Policy first: under the default (human) a reviewer grant would do nothing and mislead. Read from
3968
3969
  // THIS checkout (trunk at rest), never the branch — a branch must not raise its own grant policy.
3969
- // #596: three levels — this checkout's key > the owner-level value > human. The owner record is
3970
- // read only when the repo key is absent or `human` (the opt-out case needs it to say so).
3971
- const mintDoc = projectDoc(repoAbs);
3972
- const pol = migrationGrantPolicyFor(repoAbs, mintDoc, trustHumans.parseTrustHumans(mintDoc));
3970
+ // #598: three levels — this checkout's key > this machine's value > human (grant-policy.js).
3971
+ const pol = migrationGrantPolicyFor(projectDoc(repoAbs));
3973
3972
  if (!pol.valid) throw new UserError(`${pol.reason} — fix project.yml before minting a reviewer grant`);
3974
3973
  if (pol.policy !== 'reviewer') {
3975
3974
  if (pol.optedOut) {
3976
3975
  throw new UserError(`${pol.reason} — no reviewer grant is minted here. A human grant still works: \`COLAB_HUMAN=1 colab migration-grant <N> --branch <branch>\``);
3977
3976
  }
3978
- if (pol.ownerNote) {
3979
- throw new UserError(`this repo's migration-grant policy is "${pol.policy}" (absent = human), and ${pol.ownerNote} — re-run once \`colab owner-policy show\` reads it`);
3977
+ if (pol.machineNote) {
3978
+ throw new UserError(`this repo's migration-grant policy is "${pol.policy}" (absent = human), and ${pol.machineNote} — re-set it with \`COLAB_HUMAN=1 colab config set migration-grant <human|reviewer>\``);
3980
3979
  }
3981
3980
  throw new UserError(`this repo's migration-grant policy is "${pol.policy}"${pol.declared ? '' : ' (absent = human)'} — a reviewer grant is minted only where project.yml declares migration-grant: reviewer`);
3982
3981
  }
@@ -4111,7 +4110,7 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
4111
4110
  print(' Bound to that HEAD: any new commit voids it. It expires the moment the issue closes.');
4112
4111
  }
4113
4112
  print(` colab ship honours it only while the "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job has passed on that HEAD and the policy still says reviewer.`);
4114
- if (opts.policyResolved && opts.policyResolved.source === 'owner') print(` Policy source: ${opts.policyResolved.reason}.`);
4113
+ if (opts.policyResolved && opts.policyResolved.source === 'machine') print(` Policy source: ${opts.policyResolved.reason}.`);
4115
4114
  print(` Revoke any time: colab migration-grant ${num} --revoke`);
4116
4115
  return 0;
4117
4116
  }
@@ -4184,16 +4183,15 @@ function cmdMigrationGrantList(opts) {
4184
4183
  grants.push(row);
4185
4184
  }
4186
4185
 
4187
- // #596: the policy these grants are judged under, with its source (repo | owner | default).
4188
- const listDoc = projectDoc(repoAbs);
4189
- const pol = migrationGrantPolicyFor(repoAbs, listDoc, trustHumans.parseTrustHumans(listDoc));
4186
+ // #598: the policy these grants are judged under, with its source (repo | machine | default).
4187
+ const pol = migrationGrantPolicyFor(projectDoc(repoAbs));
4190
4188
  const policy = { value: pol.policy, source: pol.source, optedOut: pol.optedOut,
4191
- ...(pol.source === 'owner' ? { owner: pol.owner, by: pol.ownerBy, at: pol.ownerAt } : {}) };
4189
+ ...(pol.source === 'machine' ? { by: pol.machineBy, at: pol.machineAt, host: pol.machineHost } : {}) };
4192
4190
  if (opts.json) {
4193
4191
  return print(JSON.stringify({ repo: shortRepo(repoAbs), label: labels.MIGRATION_GRANT_LABEL, policy, grants, stale }, null, 2));
4194
4192
  }
4195
- // Prose names the source only where the owner level is in play — otherwise byte-identical.
4196
- if (pol.source === 'owner' || pol.optedOut || pol.ownerNote) print(`migration-grant policy: ${pol.policy} (source: ${ownerPolicy.sourceLabel(pol)}) — ${pol.reason}`);
4193
+ // Prose names the source only where the machine level is in play — otherwise byte-identical.
4194
+ if (pol.source === 'machine' || pol.optedOut || pol.machineNote) print(`migration-grant policy: ${pol.policy} (source: ${grantPolicy.sourceLabel(pol)}) — ${pol.reason}`);
4197
4195
 
4198
4196
  if (grants.length === 0 && stale.length === 0) {
4199
4197
  print(`no outstanding migration grants in ${shortRepo(repoAbs)}`);
@@ -4211,34 +4209,25 @@ function cmdMigrationGrantList(opts) {
4211
4209
  }
4212
4210
 
4213
4211
  // ---------------------------------------------------------------------------
4214
- // owner-policy (#596) — an owner-level `migration-grant` value, set once by a human for every repo
4215
- // the GitHub owner runs. Record + proof rules: tools/lib/owner-policy.js. This section is gh I/O.
4216
- // Precedence everywhere: the repo's own key > the owner value > human.
4212
+ // owner-policy (#596) — RETIRED as a resolution rung by #598. `show` still reads the owner record,
4213
+ // read-only, and says it is not honoured; `set` refuses. The policy resolves repo key > this
4214
+ // machine's value > human (tools/lib/grant-policy.js; `colab config set migration-grant`).
4217
4215
 
4218
4216
  const HELP_OWNER_POLICY = `colab owner-policy [show] [--json] [--repo <path>]
4219
- COLAB_HUMAN=1 colab owner-policy set migration-grant <human|reviewer|unset> [--repo <path>]
4220
4217
 
4221
- The owner-level grant policy (#596): ONE value for every repo the GitHub owner runs, so a new repo
4222
- does not silently start at \`human\` and the owner does not land one project.yml commit per repo.
4218
+ The owner-level grant policy (#596) is RETIRED (#598). No gate reads it. It was a marker comment
4219
+ on the open \`${ownerPolicy.LABEL}\`-labelled issue in <owner>/${ownerPolicy.RECORD_REPO}, accepted from any
4220
+ owner or org MEMBER — and the shared account agent sessions post from is typically a member, so one
4221
+ raw API call (which no COLAB_HUMAN bar can see) switched reviewer grants on for every repo.
4223
4222
 
4224
- Precedence (read by \`colab migration-grant\` when minting and \`colab ship\` when gating):
4223
+ The policy now resolves, everywhere (\`colab migration-grant\` when minting and listing, \`colab ship\`):
4225
4224
  1. the repo's own \`migration-grant:\` in project.yml — \`human\` there opts the repo out
4226
- 2. the owner-level value set here
4225
+ 2. this MACHINE's value: COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>
4227
4226
  3. the default, \`human\`
4228
4227
 
4229
- Where it lives: marker comments on the open \`${ownerPolicy.LABEL}\`-labelled issue in the owner's
4230
- \`${ownerPolicy.RECORD_REPO}\` repo (<owner>/${ownerPolicy.RECORD_REPO}). The latest marker per key whose author
4231
- is the owner or an org MEMBER — and, where the judged repo declares trust-humans, a listed login —
4232
- wins. A marker from anyone else is ignored and shown here, never honoured.
4233
-
4234
- show print the owner value, who set it and when, and what THIS repo resolves to
4235
- set K V post a new marker. Human-only: refused without COLAB_HUMAN=1, exit 1. Never
4236
- reachable through \`colab config set\` — migration-grant stays an authority key there.
4237
- \`unset\` withdraws the owner value. The ${ownerPolicy.RECORD_REPO} repo must exist —
4238
- colab never creates a repo; the issue and label are created on the first set.
4239
-
4240
- Only \`migration-grant\` is an owner-level key today. Nothing else about a reviewer grant changes:
4241
- review record, CI round-trip job, HEAD binding and revoke are exactly as before.
4228
+ show print any owner value still standing (marked: not honoured) and what THIS repo resolves
4229
+ to now, with its source (repo | machine | default)
4230
+ set refused, always — set this machine's value instead (above)
4242
4231
  `;
4243
4232
 
4244
4233
  /** The `<owner>/.github` REST paths, with gh's {owner} placeholder — resolved from the repo's remote. */
@@ -4283,14 +4272,13 @@ function ownerPolicyRead(repoAbs, trust, key = 'migration-grant') {
4283
4272
  }
4284
4273
 
4285
4274
  /**
4286
- * #596: the migration-grant policy for a repo, three levels. `doc` is the project.yml that counts
4287
- * (the trunk checkout for a mint, the merge target for ship). The owner record is read only when the
4288
- * repo key is absent or a valid `human` — a declared reviewer needs no lookup.
4275
+ * #598: the migration-grant policy for a repo — repo key > this machine's value > human. `doc` is
4276
+ * the project.yml that counts (the trunk checkout for a mint, the merge target for ship). The SAME
4277
+ * exported function a console imports (grant-policy.js effectiveGrantPolicy), so they cannot differ.
4278
+ * The owner-level record (#596) is not read here: retired as a rung.
4289
4279
  */
4290
- function migrationGrantPolicyFor(repoAbs, doc, trust) {
4291
- const repoPol = migrationGrant.parseGrantPolicy(doc);
4292
- const needOwner = !repoPol.declared || (repoPol.valid && repoPol.policy === 'human');
4293
- return ownerPolicy.resolveGrantPolicy(repoPol, needOwner ? ownerPolicyRead(repoAbs, trust) : null);
4280
+ function migrationGrantPolicyFor(doc) {
4281
+ return grantPolicy.effectiveGrantPolicy(doc);
4294
4282
  }
4295
4283
 
4296
4284
  function cmdOwnerPolicy(argv) {
@@ -4301,19 +4289,10 @@ function cmdOwnerPolicy(argv) {
4301
4289
  if (opts.help) return print(HELP_OWNER_POLICY);
4302
4290
  const sub = opts._[0] || 'show';
4303
4291
  if (sub === 'set') {
4304
- // HUMAN-ONLY, first — before resolveRepo or any gh call. Same bar as minting a grant.
4305
- if (process.env.COLAB_HUMAN !== '1') {
4306
- process.stderr.write('✗ Refusing: setting the owner-level grant policy requires a human.\n');
4307
- process.stderr.write(' Re-run with COLAB_HUMAN=1. (No field, flag or config value can lower this bar.)\n');
4308
- return 1;
4309
- }
4310
- const [, key, value] = opts._;
4311
- if (!ownerPolicy.KEYS.includes(key)) throw new UserError(`owner-policy set: key ${JSON.stringify(key)} — expected one of ${ownerPolicy.KEYS.join(' | ')}`);
4312
- if (!ownerPolicy.isValidValue(key, value)) throw new UserError(`owner-policy set ${key}: value ${JSON.stringify(value)} — expected one of ${[...ownerPolicy.VALUES[key], ownerPolicy.UNSET].join(' | ')}`);
4313
- const repoAbs = resolveRepoOrCwd(opts);
4314
- if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4315
- if (!isGhUsable(repoAbs)) throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — the owner policy lives on the tracker`);
4316
- return cmdOwnerPolicySet(repoAbs, key, value);
4292
+ // #598: retired. Refused whether or not COLAB_HUMAN is set — nothing is read or posted.
4293
+ process.stderr.write('✗ Refusing: the owner-level grant policy is retired (#598) — no gate reads it, so setting it would do nothing.\n');
4294
+ process.stderr.write(' Set this machine\'s value instead: COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>\n');
4295
+ return 1;
4317
4296
  }
4318
4297
  if (sub !== 'show') throw new UserError(`unknown owner-policy subcommand "${sub}" — expected one of show | set`);
4319
4298
  const repoAbs = resolveRepoOrCwd(opts);
@@ -4322,47 +4301,22 @@ function cmdOwnerPolicy(argv) {
4322
4301
  const doc = projectDoc(repoAbs);
4323
4302
  const trust = trustHumans.parseTrustHumans(doc);
4324
4303
  const owner = ownerPolicyRead(repoAbs, trust);
4325
- const res = ownerPolicy.resolveGrantPolicy(migrationGrant.parseGrantPolicy(doc), owner);
4304
+ const res = migrationGrantPolicyFor(doc);
4326
4305
  const out = {
4327
4306
  repo: shortRepo(repoAbs),
4328
- owner: { read: owner.read, owner: owner.owner || null, issue: owner.issue || null, why: owner.why || null,
4307
+ owner: { retired: true, read: owner.read, owner: owner.owner || null, issue: owner.issue || null, why: owner.why || null,
4329
4308
  'migration-grant': owner.set ? { value: owner.value, by: owner.by, at: owner.at } : null, ignored: owner.ignored || [] },
4330
4309
  resolved: { 'migration-grant': { policy: res.policy, source: res.source, valid: res.valid, optedOut: res.optedOut, reason: res.reason } },
4331
4310
  };
4332
4311
  if (opts.json) return print(JSON.stringify(out, null, 2));
4333
4312
  const where = owner.owner ? `${owner.owner}/${ownerPolicy.RECORD_REPO}#${owner.issue}` : `<owner>/${ownerPolicy.RECORD_REPO}`;
4334
4313
  if (owner.read === 'unread') warn(`could not read the owner record (${owner.why}) — read as unset`);
4335
- print(`owner-level migration-grant: ${owner.set ? `${owner.value} — set by ${owner.by} at ${owner.at} (${where})` : `not set (${owner.why || where})`}`);
4314
+ print(`owner-level migration-grant: ${owner.set ? `${owner.value} — set by ${owner.by} at ${owner.at} (${where})` : `not set (${owner.why || where})`} — retired (#598), not honoured`);
4336
4315
  for (const i of owner.ignored || []) warn(`ignored marker ${i.value} by ${i.login || '(unknown)'} at ${i.at}: ${i.reason}`);
4337
- print(`${shortRepo(repoAbs)} resolves to: ${res.policy} (source: ${ownerPolicy.sourceLabel(res)}) — ${res.reason}`);
4338
- return 0;
4339
- }
4340
-
4341
- function cmdOwnerPolicySet(repoAbs, key, value) {
4342
- let loc = ownerRecordIssue(repoAbs);
4343
- if (loc.read === 'unread') throw new UserError(`could not read the owner record (${loc.why}) — nothing was posted; re-run once \`colab owner-policy show\` reads it`);
4344
- if (loc.read === 'none') {
4345
- // Is the .github repo there at all? colab never creates a repo — that is the owner's call.
4346
- const repoR = git.ghApi(repoAbs, [`repos/{owner}/${ownerPolicy.RECORD_REPO}`, '--jq', '.full_name']);
4347
- if (!repoR.ok) {
4348
- throw new UserError(`the owner has no ${ownerPolicy.RECORD_REPO} repo (${ghFirstLine(repoR.stderr)}) — nothing was posted. colab never creates a repo: the owner must create <owner>/${ownerPolicy.RECORD_REPO} (GitHub's owner-wide defaults repo), then re-run`);
4349
- }
4350
- git.ghApi(repoAbs, ['-X', 'POST', `repos/{owner}/${ownerPolicy.RECORD_REPO}/labels`, '-f', `name=${ownerPolicy.LABEL}`,
4351
- '-f', 'color=5319E7', '-f', 'description=colab owner-level policy record (#596) — human-set markers only']);
4352
- const body = 'The owner-level colab policy record. Each value is a marker comment posted by `COLAB_HUMAN=1 colab owner-policy set`; ' +
4353
- 'the latest one from the owner or an org member wins. Do not close this issue — closing it withdraws every owner value.';
4354
- const created = git.ghApi(repoAbs, ['-X', 'POST', `repos/{owner}/${ownerPolicy.RECORD_REPO}/issues`, '-f', `title=${ownerPolicy.ISSUE_TITLE}`,
4355
- '-f', `body=${body}`, '-f', `labels[]=${ownerPolicy.LABEL}`, '--jq', '.number']);
4356
- if (!created.ok) throw new UserError(`could not create the owner record issue (${ghFirstLine(created.stderr)}) — nothing was posted; check write access with \`gh auth status\`, then re-run`);
4357
- loc = { read: 'ok', issue: Number(created.stdout.trim()), owner: null };
4316
+ print(`${shortRepo(repoAbs)} resolves to: ${res.policy} (source: ${grantPolicy.sourceLabel(res)}) — ${res.reason}`);
4317
+ if (owner.set && owner.value === 'reviewer' && res.source === 'default') {
4318
+ print(' To keep reviewer grants for repos without their own key, set it on this machine: COLAB_HUMAN=1 colab config set migration-grant reviewer');
4358
4319
  }
4359
- const iso = nowISO();
4360
- const c = git.ghApi(repoAbs, ['-X', 'POST', ownerRecordPath(`issues/${loc.issue}/comments`),
4361
- '-f', `body=${ownerPolicy.markerBody(key, value, commentHost(repoAbs), iso)}`]);
4362
- if (!c.ok) throw new UserError(`could not post the owner policy marker (${ghFirstLine(c.stderr)}) — nothing changed; check write access with \`gh auth status\`, then re-run`);
4363
- print(`Recorded owner-level ${key}: ${value} on ${loc.owner ? `${loc.owner}/` : '<owner>/'}${ownerPolicy.RECORD_REPO}#${loc.issue} at ${iso}.`);
4364
- print(` Repos that declare their own ${key}: are unaffected; \`${key}: human\` in a repo opts it out.`);
4365
- print(' Check what a repo resolves to: colab owner-policy show');
4366
4320
  return 0;
4367
4321
  }
4368
4322
 
@@ -7975,6 +7929,11 @@ const HELP_CONFIG = `colab config [show|add-repo <path>|rm-repo <path>|add-reser
7975
7929
  rm-notify-url <url> remove one receiver from notifyUrl; removing the last unsets the key
7976
7930
  set <key> <value> set claimTTLHours | plannerClaimTTLMinutes | portRange | worktreeSubdir | notifyUrl | journal |
7977
7931
  claimIdentity
7932
+ set migration-grant <human|reviewer|unset> [--by <name>]
7933
+ this MACHINE's migration-grant policy (#598) — HUMAN-ONLY, refused without
7934
+ COLAB_HUMAN=1; records who, when, host and machine. Repos that declare
7935
+ their own migration-grant: win; repos without one resolve to this value,
7936
+ else human. Not the repo's key — that stays an authority key (below).
7978
7937
  set <tuning-key> <value> --evidence "<why>"
7979
7938
  a kebab-case key is this REPO's .github/project.yml, not this machine (#561):
7980
7939
  one tuning value, committed on a short branch, shippable with no issue —
@@ -8025,6 +7984,7 @@ asserted — and, like docs-only (#345), it opens the autonomy gate on a repo wi
8025
7984
  Every other precondition still applies.
8026
7985
 
8027
7986
  Never on this path (they grant authority or change what deploys): ${configSet.AUTHORITY_KEYS.join(', ')}.
7987
+ (\`colab config set migration-grant <v>\` is a different command: THIS MACHINE's value, human-only, #598.)
8028
7988
 
8029
7989
  --evidence <text> the measurement behind the number (required)
8030
7990
  --no-push create the branch locally only
@@ -8091,13 +8051,52 @@ function cmdConfigSetDescriptor(argv) {
8091
8051
  return 0;
8092
8052
  }
8093
8053
 
8054
+ /**
8055
+ * #598: `config set migration-grant <human|reviewer|unset>` — THIS MACHINE's migration-grant
8056
+ * policy, stored in config.json `policy["migration-grant"]` (tools/lib/grant-policy.js). Routed here
8057
+ * before the descriptor path: there `migration-grant` is an authority key and is refused, so the
8058
+ * command had no meaning until now. HUMAN-ONLY, checked first — before any argument is parsed.
8059
+ */
8060
+ function cmdConfigSetMachinePolicy(argv) {
8061
+ if (process.env.COLAB_HUMAN !== '1') {
8062
+ process.stderr.write('✗ Refusing: setting the machine-level migration-grant policy requires a human.\n');
8063
+ process.stderr.write(' Re-run with COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>. (No field, flag or project.yml value can lower this bar.)\n');
8064
+ return 1;
8065
+ }
8066
+ const opts = parseArgs(argv, {
8067
+ values: { '--by': 'by', '--repo': 'repo', '--evidence': 'evidence' },
8068
+ flags: { '--dry': 'dry', '--no-push': 'noPush' },
8069
+ });
8070
+ if (opts.repo || opts.evidence || opts.dry || opts.noPush) {
8071
+ throw new UserError('migration-grant here is this MACHINE\'s value — --repo/--evidence/--dry/--no-push do not apply; re-run as `COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset> [--by <name>]`. A repo\'s own migration-grant: is an authority key: edit .github/project.yml on a branch with an issue');
8072
+ }
8073
+ const value = opts._[1]; // opts._[0] is migration-grant — cmdConfig routes here on exactly that key
8074
+ const allowed = [...grantPolicy.VALUES, grantPolicy.UNSET];
8075
+ if (!allowed.includes(value)) throw new UserError(`config set migration-grant: value ${JSON.stringify(value)} — expected one of ${allowed.join(' | ')}`);
8076
+ let by = opts.by;
8077
+ if (!by) { try { by = os.userInfo().username; } catch (_) { by = null; } }
8078
+ const iso = nowISO();
8079
+ const meta = { by: by || null, at: iso, host: os.hostname(), machine: myMachineId() };
8080
+ state.saveConfig(grantPolicy.withValue(state.loadConfig(), value, meta));
8081
+ if (value === grantPolicy.UNSET) {
8082
+ print('migration-grant (machine) = (unset) — repos without their own key fall back to human');
8083
+ } else {
8084
+ print(`migration-grant (machine) = ${value} — set by ${meta.by || '?'} at ${iso} on ${meta.host}`);
8085
+ print(' Repos that declare their own migration-grant: are unaffected; migration-grant: human in a repo opts it out. Check: colab migration-grant --list');
8086
+ }
8087
+ return 0;
8088
+ }
8089
+
8094
8090
  function cmdConfig(argv) {
8095
8091
  const sub = argv[0];
8092
+ if (sub === 'set' && argv[1] === grantPolicy.MACHINE_KEY) return cmdConfigSetMachinePolicy(argv.slice(1)); // #598, human gate first
8096
8093
  const cfg = state.loadConfig();
8097
8094
  if (!sub || sub === 'show') {
8098
8095
  print(`state: ${state.STATE_FILE}`);
8099
8096
  print(`config: ${state.CONFIG_FILE}`);
8100
8097
  print(JSON.stringify(cfg, null, 2));
8098
+ const mp = grantPolicy.readMachinePolicy();
8099
+ print(`migration-grant (machine): ${mp.read === 'ok' ? `${mp.value} — set by ${mp.by || '?'} at ${mp.at || '?'} on ${mp.host || '?'}` : mp.read === 'none' ? 'not set' : `not usable — ${mp.why}`}`);
8101
8100
  const reserved = ports.reservedSet(cfg, knownRepos(cfg));
8102
8101
  print(`reserved ports (${reserved.size}): ${[...reserved.keys()].sort((a, b) => a - b).join(', ') || '—'}`);
8103
8102
  return 0;
@@ -10375,10 +10374,9 @@ function shipMigrationGate(repoAbs, gh, target, branch, issues) {
10375
10374
  /** P, HEAD and the R thunk for shipMigrationGate. The thunk memoises its one verdict on the ctx
10376
10375
  * (`roundtripResult`) so the payload can report what R saw without a second read. */
10377
10376
  function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
10378
- // #596: the target's key > the owner-level value > human. `trust` (the target's trust-humans)
10379
- // also judges who wrote the owner record.
10377
+ // #598: the target's key > this machine's value > human.
10380
10378
  const trust = trustAt(repoAbs, target);
10381
- const pres = migrationGrantPolicyFor(repoAbs, projectDocAt(repoAbs, target), trust);
10379
+ const pres = migrationGrantPolicyFor(projectDocAt(repoAbs, target));
10382
10380
  const policy = pres.policy;
10383
10381
  const remote = git.remoteInfo(repoAbs).name || 'origin';
10384
10382
  const ls = git.git(['ls-remote', remote, `refs/heads/${branch}`], repoAbs);
@@ -10393,8 +10391,8 @@ function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
10393
10391
  const contentId = headSha ? migrationContentAt(repoAbs, migrations, headSha) : null;
10394
10392
  const ctx = { policy, headSha, contentId, headNote, roundtripResult: null, trust,
10395
10393
  policySource: pres.source, policyRes: pres,
10396
- // Only where the owner level is in play: the default/repo refusal text stays byte-identical.
10397
- policyReason: pres.source === 'owner' || pres.optedOut || pres.ownerNote ? pres.reason : null,
10394
+ // Only where the machine level is in play: the default/repo refusal text stays byte-identical.
10395
+ policyReason: pres.source === 'machine' || pres.optedOut || pres.machineNote ? pres.reason : null,
10398
10396
  labelActors: (n) => git.ghIssueLabelActors(repoAbs, n, labels.MIGRATION_GRANT_LABEL) };
10399
10397
  ctx.roundtrip = () => {
10400
10398
  const d = git.git(['diff', '--name-only', `${target}...${branch}`], repoAbs);
@@ -10427,10 +10425,12 @@ function migDetail(migrations, grants, target, branch, ctx) {
10427
10425
  const payload = {
10428
10426
  branch, files: [...migrations],
10429
10427
  policy: ctx ? ctx.policy : null,
10430
- // #596: where the policy came from — repo | owner | default — and, for owner, who set it when.
10428
+ // #598: where the policy came from — repo | machine | default — and, for machine, who set it when.
10431
10429
  policySource: ctx ? ctx.policySource || null : null,
10432
- policyOwner: ctx && ctx.policyRes && ctx.policyRes.source === 'owner'
10433
- ? { owner: ctx.policyRes.owner, by: ctx.policyRes.ownerBy, at: ctx.policyRes.ownerAt } : null,
10430
+ // #596's field, kept for additive-only consumers: always null now that the owner level is retired.
10431
+ policyOwner: null,
10432
+ policyMachine: ctx && ctx.policyRes && ctx.policyRes.source === 'machine'
10433
+ ? { by: ctx.policyRes.machineBy, at: ctx.policyRes.machineAt, host: ctx.policyRes.machineHost } : null,
10434
10434
  headSha: ctx ? ctx.headSha : null,
10435
10435
  contentId: ctx ? ctx.contentId || null : null,
10436
10436
  // #407: the human list as read from the TARGET — null when undeclared (association class).
@@ -10444,8 +10444,8 @@ function migDetail(migrations, grants, target, branch, ctx) {
10444
10444
  if (grants.ok) {
10445
10445
  const by = grants.granted.map((g) => (g.role === 'reviewer' ? `#${g.issue} (reviewer ${g.reviewer} @ ${String(g.head).slice(0, 7)}${g.via === 'content' ? `, migration content ${String(g.migrations).slice(0, 12)} unchanged since` : ''}, CI round-trip passed)` : '#' + g.issue)).join(' ');
10446
10446
  const roles = [...new Set(grants.granted.map((g) => g.role || 'human'))].join('+');
10447
- const src = ctx && ctx.policySource === 'owner' && grants.granted.some((g) => g.role === 'reviewer')
10448
- ? ` (policy: ${ownerPolicy.sourceLabel(ctx.policyRes)})` : '';
10447
+ const src = ctx && ctx.policySource === 'machine' && grants.granted.some((g) => g.role === 'reviewer')
10448
+ ? ` (policy: ${grantPolicy.sourceLabel(ctx.policyRes)})` : '';
10449
10449
  return { text: `${migrations.length} present, exempted by a ${roles} grant on ${by} for branch "${branch}"${src} — ${files}`, payload };
10450
10450
  }
10451
10451
  // Each missing entry already carries its own specific, actionable reason (evaluateShipSet) —
@@ -10582,7 +10582,7 @@ function ciCureTrailerLine(cureVerdict, branch, trunk) {
10582
10582
  }
10583
10583
 
10584
10584
  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]
10585
- colab ship --batch <b1,b2[,…]> [--split] [--repo <path>] [--keep-worktree] [--delete-branch | --keep-branch] [--session <id>] [--session-name <s>] [--dry]
10585
+ colab ship --batch <b1,b2[@<handoff-url>][,…]> [--split] [--repo <path>] [--keep-worktree] [--delete-branch | --keep-branch] [--session <id>] [--session-name <s>] [--dry]
10586
10586
 
10587
10587
  The ONE sanctioned door for code-wrap Phase B: squash-merge a session branch into the BASE IT WAS
10588
10588
  CUT FROM — trunk for an ordinary session, or the declared integration line recorded on its worktree
@@ -10687,8 +10687,15 @@ live \`🔒 Claimed\` comment on that branch, posted by the hand-off's author be
10687
10687
  claimed or taken over here: the executor keeps its claim, worktree and branch until it confirms
10688
10688
  the land, the shipped branch is kept, the squash carries \`Colab-Handoff: <url> @ <sha>\`, and each
10689
10689
  🚢 comment names the hand-off. Any check failing refuses (exit 1); --force is never involved, and
10690
- the human takeover (\`colab claim --force\`) stays the only other way in. Not with --adopt,
10691
- --batch or --direct, and not when this machine already holds a claim on the branch.
10690
+ the human takeover (\`colab claim --force\`) stays the only other way in. Not with --adopt
10691
+ or --direct, and not when this machine already holds a claim on the branch.
10692
+
10693
+ IN A BATCH (#591) the hand-off rides its member: \`--batch b1,b2@<url>\` (split on the first @).
10694
+ That member is verified by this SAME door — same checks, same refusal text, which drops it from
10695
+ the batch while the rest build — then joins the combined run with no sync of its own; its squash
10696
+ carries the Colab-Handoff trailer, and the land reads the door back from that commit. Repeat the
10697
+ same list, @ included, on every call: a rebuild re-verifies its members from the command line.
10698
+ A bare --handoff beside --batch names no member and refuses.
10692
10699
 
10693
10700
  A remote-built branch that fell BEHIND its base (#579) is synced by the lander as usual (B0: merge
10694
10701
  the base in, push) — and the hand-off still verifies, because the commits between the handed-off
@@ -12306,6 +12313,11 @@ function cmdShipDryJson(opts) {
12306
12313
  baseCi: baseCiPayloadVal, dirtyOwners: dirtyOwnersPayloadVal, autonomyGate: autonomyGatePayloadVal,
12307
12314
  coreReview: coreReviewPayloadVal,
12308
12315
  ...machineTrailerPayload(mode === 'squash' || mode === 'pr-pending'),
12316
+ // #591: the verified hand-off (or its refusal), so `ship --batch` puts this member's
12317
+ // Colab-Handoff trailer on its squash and words a refusal exactly as the single door does.
12318
+ ...(handoff ? { handoff: handoff.ok
12319
+ ? { ok: true, url: handoff.url, sha: handoff.sha, handedOff: handoff.handedOff, syncMerges: handoff.syncMerges || 0 }
12320
+ : { ok: false, reason: handoff.reason, detail: handoff.detail } } : {}),
12309
12321
  };
12310
12322
  // #373: `ship --batch` reads each member through this SAME function — handed the body, not stdout.
12311
12323
  if (opts._report) opts._report.body = body;
@@ -12467,11 +12479,14 @@ function cmdShipDryJson(opts) {
12467
12479
  // ---- (c) no hand-merge conflict — NEW: the plain --dry prose path never checks this today ----
12468
12480
  const generated = [...DEFAULT_GENERATED, ...(Array.isArray(doc.generated) ? doc.generated.map(String) : [])];
12469
12481
  const hasPreShip = fs.existsSync(path.join(repoAbs, '.colab', 'hooks', 'pre-ship'));
12470
- const mc = shipMergeConflictCheck(repoAbs, target, sess.branch, generated, hasPreShip);
12482
+ // #591: read the branch through the ref it actually resolves to — a hand-off branch is remote-only
12483
+ // here, and its bare name resolves to nothing (the same gap #589 closed for the cure rule).
12484
+ const dryShipRef = shipRefFor(repoAbs, sess.branch);
12485
+ const mc = shipMergeConflictCheck(repoAbs, target, dryShipRef, generated, hasPreShip);
12471
12486
  checks.push({ name: 'no hand-merge conflict', ok: mc.ok, class: mc.ok ? null : (mc.unknown ? SELF_CLEARING : HUMAN_GATED), detail: mc.detail });
12472
12487
 
12473
12488
  // ---- (d) the two checks the machine-facing path was missing entirely ----
12474
- const dryCommits = branchCommits(repoAbs, target, sess.branch);
12489
+ const dryCommits = branchCommits(repoAbs, target, dryShipRef);
12475
12490
 
12476
12491
  // #87: B1b's cross-check, same rule as the prose path — only over the issues that would CLOSE.
12477
12492
  const dryCorr = shipguard.corroborateIssues(closeIssues, sess.branch, dryCommits);
@@ -12514,7 +12529,7 @@ function cmdShipDryJson(opts) {
12514
12529
  // #90: "branch has commits" — the precondition whose absence told an unattended caller `ok: true`
12515
12530
  // about a branch that could not ship. It is NOT a failure when the branch qualifies for
12516
12531
  // evidence-close; it is a different mode, and saying so is the whole point.
12517
- const dryMode = shipMode(repoAbs, target, sess.branch, dryCommits);
12532
+ const dryMode = shipMode(repoAbs, target, dryShipRef, dryCommits);
12518
12533
  if (dryMode.evidenceClose) {
12519
12534
  mode = 'evidence-close';
12520
12535
  checks.push({ name: 'branch has commits', ok: true, class: null,
@@ -13422,8 +13437,10 @@ function cmdShip(argv) {
13422
13437
  // — refuse the combination rather than silently ignore --json on a real ship.
13423
13438
  if (opts.json && !opts.dry) throw new UserError('--json currently only applies together with --dry — see `colab ship --help`');
13424
13439
  if (shippedBranch.conflictingFlags(opts)) throw new UserError('--delete-branch and --keep-branch contradict each other — pass one (see `colab ship --help`, #368)');
13425
- // #578: a hand-off names ONE branch; batch and trunk-direct have no single branch for it to name.
13426
- 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\`)`);
13440
+ // #578: a hand-off names ONE branch; trunk-direct has no branch for it to name. #591: in a batch the
13441
+ // hand-off rides its member (`--batch b1,b2@<url>`), so a bare --handoff beside --batch names no one.
13442
+ if (opts.handoff && opts.batch) throw new UserError('--handoff names one --branch ship; in a batch, attach it to its member: --batch <b1>,<b2>@<hand-off-url> (#591, see `colab ship --help`)');
13443
+ if (opts.handoff && opts.direct) throw new UserError('--handoff applies to one --branch ship — not to --direct (see `colab ship --help`)');
13427
13444
  if (opts.split && !opts.batch) throw new UserError('--split applies to a red combined run of --batch only (#557) — run `colab ship --batch <b1,b2,…> --split` with the members the red batch carries');
13428
13445
  if (opts.batch) return cmdShipBatch(opts); // #373 — its own re-entrant path; nothing below changes
13429
13446
  // A fully separate code path, deliberately: the prose/table path below is unchanged by this
@@ -14694,7 +14711,11 @@ function cmdShipBatch(opts) {
14694
14711
  const doc = projectDoc(repoAbs);
14695
14712
  const trunk = resolveTrunk(repoAbs, doc);
14696
14713
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
14697
- const members = [...new Set(String(opts.batch === true ? '' : opts.batch).split(',').map((s) => s.trim()).filter(Boolean))];
14714
+ // #591: a member built on another machine names its hand-off inline — `<branch>@<hand-off-url>`.
14715
+ const entries = shipHandoff.parseBatchEntries(opts.batch === true ? '' : opts.batch);
14716
+ if (entries.errors.length) throw new UserError(`--batch: ${entries.errors.join('; ')}`);
14717
+ const members = entries.members;
14718
+ const handoffs = entries.handoffs;
14698
14719
  if (members.includes(trunk)) throw new UserError(`Refusing: ${trunk} is the trunk itself — it cannot be a batch member`);
14699
14720
  const serial = (why, list = members) => {
14700
14721
  print(`✗ ship-batch: ${why}`);
@@ -14865,13 +14886,19 @@ function cmdShipBatch(opts) {
14865
14886
  if (!refs.remoteSha) why = `not on ${remote} — push it first; its CI has never seen it`;
14866
14887
  else if (refs.localSha && refs.localSha !== refs.remoteSha) why = `local ${shortSha(refs.localSha)} ≠ ${remote} ${shortSha(refs.remoteSha)} — its CI never saw this head`;
14867
14888
  if (!why) {
14868
- const rep = shipDryJsonReport({ repo: repoAbs, branch: b, dry: true, json: true, session: opts.session, sessionName: opts.sessionName });
14889
+ // #591: a hand-off member is read through the SAME door a single --handoff ship uses
14890
+ // (applyShipHandoff inside cmdShipDryJson) — one verification, never a batch-local copy.
14891
+ const rep = shipDryJsonReport({ repo: repoAbs, branch: b, dry: true, json: true, session: opts.session, sessionName: opts.sessionName,
14892
+ ...(handoffs[b] ? { handoff: handoffs[b] } : {}) });
14869
14893
  report = rep.body;
14870
14894
  files = branchChangedFiles(repoAbs, trunkRef, refs.remoteSha);
14871
14895
  ciClass = shipBatch.branchCiClass(git.ghRunForSha(repoAbs, b), workflowsFiringAt(repoAbs, refs.remoteSha, b).length > 0);
14872
- const el = rep.error ? { ok: false, why: rep.error } : shipBatch.memberEligibility(report, ciClass, {
14873
- trunk, touchesWorkflows: files.some((f) => f.startsWith('.github/workflows/')),
14874
- });
14896
+ const el = rep.error ? { ok: false, why: rep.error }
14897
+ // #591: a refused hand-off is worded as the single door words it — the same reason, the same detail.
14898
+ : (report && report.handoff && !report.handoff.ok) ? { ok: false, why: `Refusing --handoff: ${report.handoff.detail}` }
14899
+ : shipBatch.memberEligibility(report, ciClass, {
14900
+ trunk, touchesWorkflows: files.some((f) => f.startsWith('.github/workflows/')),
14901
+ });
14875
14902
  if (!el.ok) why = el.why;
14876
14903
  }
14877
14904
  evaluated.push({ branch: b, sha: refs.remoteSha, report, ciClass, files, ok: !why, why: why || `own head CI: ${ciClass}` });
@@ -14969,8 +14996,9 @@ function cmdShipBatch(opts) {
14969
14996
  const closeIssues = m.report.closeIssues || [];
14970
14997
  const refsIssues = m.report.refsIssues || [];
14971
14998
  const conflicts = [];
14999
+ // #591: a hand-off member's squash records the door its issue set came through, as a single ship's does.
14972
15000
  const msg = buildSquashMessage(repoAbs, trunkRef, m.sha, closeIssues, refsIssues, conflicts,
14973
- [machineLine, shipBatch.memberTrailer({ ref, branch: m.branch, sha: m.sha })].filter(Boolean));
15001
+ [shipHandoff.handoffTrailer(m.report.handoff), machineLine, shipBatch.memberTrailer({ ref, branch: m.branch, sha: m.sha })].filter(Boolean));
14974
15002
  const coverage = msg ? shipguard.closesCoverage({ message: msg, closeIssues, refsIssues, commits: branchCommits(repoAbs, trunkRef, m.sha) }) : { ok: false, missing: [] };
14975
15003
  const inherited = msg && refsIssues.length ? squash.inheritedClosingKeywordConflicts(msg, refsIssues) : [];
14976
15004
  if (!msg || !coverage.ok || inherited.length) {
@@ -15117,10 +15145,26 @@ function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opt
15117
15145
  // The post-ship hook runs ONCE, over the whole batch — it is a trunk-checkout event, not a member one.
15118
15146
  const changed = git.git(['diff', '--name-only', `${base}..${head}`], repoAbs);
15119
15147
  const hits = changed.ok ? lockfileDrift.changedLockfiles(changed.stdout.split('\n').filter(Boolean)) : [];
15148
+ // Which commit is whose — read from the trailers, never from position alone.
15149
+ const log = git.git(['log', '--format=%H%x01%B%x00', `${base}..${head}`], repoAbs);
15150
+ const commitOf = new Map();
15151
+ for (const rec of (log.ok ? log.stdout.split('\0') : [])) {
15152
+ const [sha, body] = rec.replace(/^\n+/, '').split('\x01');
15153
+ const tr = shipBatch.parseMemberTrailers([body || ''])[0];
15154
+ if (sha && tr) commitOf.set(tr.branch, { sha: sha.trim(), body: body || '' });
15155
+ }
15120
15156
  const allIssues = [];
15121
15157
  const st0 = state.loadState();
15122
15158
  const sessions = existing.members.map((m) => {
15123
15159
  const sess = resolveShipSession(st0, repoAbs, { branch: m.branch, session: opts.session, sessionName: opts.sessionName });
15160
+ // #591: a hand-off member holds no claim here. Its squash carries the Colab-Handoff trailer the
15161
+ // build verified, and the issue set is the branch name's trailing run — handoffVerdict's own rule —
15162
+ // so its tail is the single hand-off land's: Closes from git, the executor's claim and branch kept.
15163
+ const ho = sess.issues.length ? null : shipHandoff.parseHandoffTrailer((commitOf.get(m.branch) || {}).body);
15164
+ if (ho) {
15165
+ sess.issues = shipguard.branchIssueNumbers(m.branch);
15166
+ sess.handoff = { ok: true, url: ho.url, sha: m.sha, handedOff: ho.handedOff };
15167
+ }
15124
15168
  allIssues.push(...sess.issues);
15125
15169
  return sess;
15126
15170
  });
@@ -15132,14 +15176,6 @@ function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opt
15132
15176
  if (hits.length && !hook.ran) warnDeferred(lockfileDrift.driftWarning(hits));
15133
15177
  release();
15134
15178
 
15135
- // Which commit is whose — read from the trailers, never from position alone.
15136
- const log = git.git(['log', '--format=%H%x01%B%x00', `${base}..${head}`], repoAbs);
15137
- const commitOf = new Map();
15138
- for (const rec of (log.ok ? log.stdout.split('\0') : [])) {
15139
- const [sha, body] = rec.replace(/^\n+/, '').split('\x01');
15140
- const tr = shipBatch.parseMemberTrailers([body || ''])[0];
15141
- if (sha && tr) commitOf.set(tr.branch, { sha: sha.trim(), body: body || '' });
15142
- }
15143
15179
  const gh = isGhUsable(repoAbs);
15144
15180
  const suffix = shipBatch.evidenceSuffix({ n: existing.members.length, ref: existing.ref, headSha: head, runIds: verdict.runIds });
15145
15181
  existing.members.forEach((m, i) => {
@@ -15171,14 +15207,16 @@ function shipBatchMemberTail({ repoAbs, doc, trunk, sess, sha, closeIssues, refs
15171
15207
  pushEvent('ship', {
15172
15208
  repo: repoAbs, worktree: sess.name, session: sess.session,
15173
15209
  issue: sess.issues.length === 1 ? sess.issues[0] : undefined,
15174
- payload: { state: 'merged', branch: sess.branch, target: trunk, sha, issues: sess.issues, batch: true },
15210
+ payload: { state: 'merged', branch: sess.branch, target: trunk, sha, issues: sess.issues, batch: true,
15211
+ ...(sess.handoff ? { handoff: { url: sess.handoff.url, sha: sess.handoff.sha } } : {}) },
15175
15212
  });
15176
15213
  for (const num of closeIssues) pushEvent('issue-merged', { repo: repoAbs, issue: num, payload: { sha } });
15177
15214
  shipLandedTail({
15178
15215
  repoAbs, sess, target: trunk, trunk, gh, sha, closeIssues, refsIssues, refsSet: new Set(refsIssues),
15179
- integration: resolveIntegration(repoAbs, doc, trunk), opts, evidenceExtra: suffix,
15216
+ integration: resolveIntegration(repoAbs, doc, trunk), opts, evidenceExtra: suffix + handoffEvidence(sess.handoff), // #591
15180
15217
  });
15181
15218
  print(` ✓ ${sess.branch} → ${trunk} @ ${sha}${sess.issues.length ? ' (' + sess.issues.map((n) => '#' + n).join(' ') + ')' : ''}`);
15219
+ 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)`);
15182
15220
  }
15183
15221
 
15184
15222
  // ---------------------------------------------------------------------------
@@ -16715,8 +16753,8 @@ Commands:
16715
16753
  blocked <blocked> --by <blocker> [--clear --reason R [--force]] [--repo P]
16716
16754
  own the blocked_by dependency-edge write (#251)
16717
16755
  migration-grant <issue> --branch B | --revoke | --list [--json] human-only ship migration exemption (#98)
16718
- owner-policy [show [--json]] | set migration-grant <human|reviewer|unset> owner-level grant policy,
16719
- every repo the GitHub owner runs; set is human-only (#596)
16756
+ owner-policy [show [--json]] the retired owner-level grant policy (#596), read-only;
16757
+ set refuses — use config set migration-grant (#598)
16720
16758
  decision <issue> --record --ruled-by N | --reopen --ruled-by N | --list [--json]
16721
16759
  record/reopen a needs-decision answer (#121, #122)
16722
16760
  ci-grant <issue> --branch B | --revoke | --list [--json] ship trunk-CI-green exemption: human, or ci-reviewer under opt-in (#105, #504)
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+ /**
3
+ * The migration-grant policy's ONE precedence (#598): the repo's explicit `migration-grant:` >
4
+ * this machine's value > `human`. Every reader resolves through here — `colab migration-grant`
5
+ * (mint and --list), `colab ship`, and any console on the same machine that imports this module —
6
+ * so none of them can compute a different answer than the gate does.
7
+ *
8
+ * THE MACHINE VALUE lives in this machine's colab config (`~/.colab/config.json`, or
9
+ * `$COLAB_HOME/config.json`), under `policy["migration-grant"]`:
10
+ * { "value": "human" | "reviewer", "by": "<who>", "at": "<ISO>", "host": "<hostname>", "machine": "<id>|null" }
11
+ * Written only by `COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>` — the
12
+ * human gate is in tools/colab, before anything is parsed. Its reach is ONE machine: a ship run on
13
+ * another machine never sees it and resolves to `human`, which is the safe direction.
14
+ * `machine` binds the record to the machine that wrote it, so a dotfile-synced or copied config
15
+ * does not carry the switch to another box (read: 'foreign'). Where either side has no machine id,
16
+ * the binding is skipped.
17
+ *
18
+ * THE OWNER-LEVEL RECORD (#596) IS NOT A RUNG. It was a tracker comment any org member could post,
19
+ * including the shared account agent sessions post from, and it reached every repo of the owner
20
+ * (#598, docs/adr/539-migration-rationale.md). `colab owner-policy show` still reads it, read-only.
21
+ *
22
+ * A CONSOLE: call `effectiveGrantPolicy(doc)` with the project.yml the gate reads (the trunk
23
+ * checkout for a mint, the merge target for ship). It reads the same config file colab does —
24
+ * pass `{ configFile }` explicitly if the console process does not inherit colab's COLAB_HOME.
25
+ *
26
+ * Everything here is pure except `readMachinePolicy` (and `effectiveGrantPolicy`, which calls it).
27
+ */
28
+ const fs = require('fs');
29
+ const migrationGrant = require('./migration-grant');
30
+
31
+ const MACHINE_KEY = 'migration-grant';
32
+ const CONFIG_SECTION = 'policy';
33
+ const VALUES = ['human', 'reviewer'];
34
+ const UNSET = 'unset';
35
+
36
+ /**
37
+ * The machine record from a parsed config.json object. Pure.
38
+ * Returns { read: 'ok'|'none'|'invalid'|'foreign', set, value, by, at, host, machine, why }.
39
+ * Anything but read 'ok' is unset.
40
+ */
41
+ function machinePolicyFrom(cfg, { machineId = null } = {}) {
42
+ const sec = cfg && typeof cfg === 'object' ? cfg[CONFIG_SECTION] : null;
43
+ const rec = sec && typeof sec === 'object' ? sec[MACHINE_KEY] : undefined;
44
+ const empty = { set: false, value: null, by: null, at: null, host: null, machine: null };
45
+ if (rec === undefined || rec === null) return { read: 'none', ...empty, why: '' };
46
+ if (typeof rec !== 'object' || Array.isArray(rec) || !VALUES.includes(rec.value)) {
47
+ return { read: 'invalid', ...empty, why: `${CONFIG_SECTION}.${MACHINE_KEY} in the machine config is not a human|reviewer record` };
48
+ }
49
+ const bits = { value: rec.value, by: rec.by || null, at: rec.at || null, host: rec.host || null, machine: rec.machine || null };
50
+ if (bits.machine && machineId && bits.machine !== machineId) {
51
+ return { read: 'foreign', ...empty, why: `the machine-level value was written on another machine (${bits.host || bits.machine}) — a copied config does not carry it` };
52
+ }
53
+ return { read: 'ok', set: true, ...bits, why: '' };
54
+ }
55
+
56
+ function defaultConfigFile() { return require('./state').CONFIG_FILE; }
57
+ function defaultMachineId() {
58
+ try { return require('./machine').localMachine().id || null; } catch (_) { return null; }
59
+ }
60
+
61
+ /** The machine record, read from disk. Never throws: an unreadable file reads as unset. */
62
+ function readMachinePolicy({ configFile, machineId } = {}) {
63
+ const file = configFile || defaultConfigFile();
64
+ let raw;
65
+ try { raw = fs.readFileSync(file, 'utf8'); } catch (e) {
66
+ if (e && e.code === 'ENOENT') return machinePolicyFrom({}, {});
67
+ return { read: 'unread', set: false, value: null, why: `${file}: ${e.message}` };
68
+ }
69
+ let cfg;
70
+ try { cfg = JSON.parse(raw); } catch (e) { return { read: 'unread', set: false, value: null, why: `${file} is not valid JSON` }; }
71
+ return machinePolicyFrom(cfg, { machineId: machineId === undefined ? defaultMachineId() : machineId });
72
+ }
73
+
74
+ /**
75
+ * The precedence. `repoPol` = migration-grant.js parseGrantPolicy(doc); `machine` = a
76
+ * machinePolicyFrom/readMachinePolicy result, or null. Returns repoPol's shape plus
77
+ * { source: 'repo'|'machine'|'default', optedOut, machineBy, machineAt, machineHost, machineNote }.
78
+ * `reason` names the source — callers print it on refusal. Pure.
79
+ */
80
+ function resolveGrantPolicy(repoPol, machine) {
81
+ const m = machine || null;
82
+ const set = !!(m && m.read === 'ok' && m.set);
83
+ const bits = set ? { machineBy: m.by || null, machineAt: m.at || null, machineHost: m.host || null }
84
+ : { machineBy: null, machineAt: null, machineHost: null };
85
+ if (repoPol.declared) {
86
+ const optedOut = repoPol.valid && repoPol.policy === 'human' && set && m.value === 'reviewer';
87
+ return { ...repoPol, source: 'repo', optedOut, ...bits, machineNote: '',
88
+ reason: optedOut
89
+ ? `this repo opted out: project.yml declares migration-grant: human, which wins over this machine's reviewer value (set by ${m.by} at ${m.at})`
90
+ : repoPol.reason };
91
+ }
92
+ if (set) {
93
+ return { policy: m.value, declared: false, valid: true, source: 'machine', optedOut: false, ...bits, machineNote: '',
94
+ reason: `machine-level migration-grant: ${m.value} (set by ${m.by || '?'} at ${m.at || '?'} on ${m.host || 'this machine'}; this repo declares no key of its own)` };
95
+ }
96
+ const machineNote = m && (m.read === 'unread' || m.read === 'invalid' || m.read === 'foreign')
97
+ ? `the machine-level value is not usable (${m.why || m.read}) — read as unset` : '';
98
+ return { ...repoPol, source: 'default', optedOut: false, ...bits, machineNote,
99
+ reason: machineNote ? `${repoPol.reason}; ${machineNote}` : repoPol.reason };
100
+ }
101
+
102
+ /** The one call a console makes: the policy for `doc`, against this machine's config. */
103
+ function effectiveGrantPolicy(doc, opts = {}) {
104
+ return resolveGrantPolicy(migrationGrant.parseGrantPolicy(doc), readMachinePolicy(opts));
105
+ }
106
+
107
+ /** One-line source label: `repo`, `machine (<by> at <at>)`, or `default`. */
108
+ function sourceLabel(res) {
109
+ if (!res) return 'default';
110
+ if (res.source === 'machine') return `machine (${res.machineBy || '?'} at ${res.machineAt || '?'})`;
111
+ return res.source;
112
+ }
113
+
114
+ /** The stored record. Pure. */
115
+ function recordFor(value, { by = null, at = null, host = null, machine = null } = {}) {
116
+ if (!VALUES.includes(value)) throw new Error(`grant-policy: ${JSON.stringify(value)} is not one of ${VALUES.join(' | ')}`);
117
+ return { value, by, at, host, machine };
118
+ }
119
+
120
+ /** A new config object with the machine value set (or removed, on `unset`). Every other key kept. Pure. */
121
+ function withValue(cfg, value, meta = {}) {
122
+ const next = { ...(cfg || {}) };
123
+ const sec = { ...(next[CONFIG_SECTION] && typeof next[CONFIG_SECTION] === 'object' ? next[CONFIG_SECTION] : {}) };
124
+ if (value === UNSET) delete sec[MACHINE_KEY];
125
+ else sec[MACHINE_KEY] = recordFor(value, meta);
126
+ if (Object.keys(sec).length) next[CONFIG_SECTION] = sec; else delete next[CONFIG_SECTION];
127
+ return next;
128
+ }
129
+
130
+ module.exports = {
131
+ MACHINE_KEY, CONFIG_SECTION, VALUES, UNSET,
132
+ machinePolicyFrom, readMachinePolicy, resolveGrantPolicy, effectiveGrantPolicy, sourceLabel, recordFor, withValue,
133
+ };
@@ -704,8 +704,8 @@ function parseGrantPolicy(doc) {
704
704
  * The reviewer-grant verdict for one issue — P, M and HEAD of the ship rule; evaluateShipSet()
705
705
  * (#401) calls it and adds R. `ctx` = { branch, headSha, contentId, issueNum, labelName, policy } where
706
706
  * `contentId` (#508) is migrationContentId at `headSha` (grantHeadBinding), and
707
- * `policy` is the resolved policy (repo key > owner-level > human, #596) and `policyReason` its
708
- * source sentence when the owner level is in play. Checks, cheapest/most-fundamental first, each with its
707
+ * `policy` is the resolved policy (repo key > machine-level > human, #598) and `policyReason` its
708
+ * source sentence when the machine level is in play. Checks, cheapest/most-fundamental first, each with its
709
709
  * own reason: read failed · not open · no label · policy not `reviewer` · no live reviewer grant ·
710
710
  * branch mismatch · untrusted author · record invalid · record not passing · HEAD binding.
711
711
  * The CI round-trip is checked here only as RECORDED; re-verifying it against live CI for `head`
@@ -720,8 +720,8 @@ function evaluateReviewerGrant(record, ctx) {
720
720
  if (record.state !== 'OPEN') return no(`#${issue} is ${record.state || 'not open'} — a grant expires when its issue closes`);
721
721
  const labelNames = (record.labels || []).map((l) => (l && typeof l === 'object' ? l.name : l));
722
722
  if (!labelNames.includes(c.labelName)) return no(`#${issue} does not carry the \`${c.labelName}\` label`);
723
- // #596: `policyReason` is set only where the owner level is in play (an owner value, a repo opt-out,
724
- // an unreadable owner record) — it names the source. Otherwise the text is the pre-#596 one.
723
+ // #598: `policyReason` is set only where the machine level is in play (a machine value, a repo
724
+ // opt-out, an unusable machine record) — it names the source. Otherwise the text is the pre-#596 one.
725
725
  if (c.policy !== 'reviewer') {
726
726
  return no(c.policyReason
727
727
  ? `${c.policyReason} — a reviewer grant is honoured only where the policy resolves to reviewer`
@@ -1,7 +1,15 @@
1
1
  'use strict';
2
2
  /**
3
- * Owner-level grant policy (#596): one `migration-grant` value set once, by a human, for every repo
4
- * an owner runs. Precedence: the repo's explicit `migration-grant:` > the owner value > `human`.
3
+ * Owner-level grant policy (#596) — RETIRED as a resolution rung by #598. No gate reads it: the
4
+ * policy resolves repo key > this machine's value > `human` (grant-policy.js). What remains here
5
+ * is the record reader `colab owner-policy show` uses, read-only, so an operator who relied on an
6
+ * owner value can see that it is no longer honoured and why. `owner-policy set` refuses.
7
+ *
8
+ * Why retired: the record is accepted from any OWNER/MEMBER comment, and the shared account agent
9
+ * sessions post from is typically an org member — one raw `gh api` POST, which skips the
10
+ * COLAB_HUMAN bar entirely, switched reviewer grants on for every repo of the owner (#407 class).
11
+ *
12
+ * As it was (#596): one `migration-grant` value set once, by a human, for every repo an owner runs.
5
13
  *
6
14
  * WHERE IT LIVES. Not in a file. A committed file (in the repo, or in the owner's `.github` repo)
7
15
  * is edited by any session that can commit, and nothing in it names who set it. So the value is a
@@ -93,41 +101,10 @@ function ownerValue(comments, key, trust) {
93
101
  return { set: true, value: cur.value, by: cur.by, at: cur.at, ignored };
94
102
  }
95
103
 
96
- /**
97
- * Three-level precedence for `migration-grant`. `repoPol` = migration-grant.js parseGrantPolicy(doc);
98
- * `owner` = { read: 'ok'|'none'|'unread', owner, set, value, by, at, why } from tools/colab's reader,
99
- * or null when the owner record was not consulted (the repo declares its own key, so it is not needed).
100
- * Returns repoPol's shape plus { source: 'repo'|'owner'|'default', optedOut, owner, ownerBy, ownerAt,
101
- * ownerNote }. `reason` is a sentence naming the source — the caller prints it on refusal.
102
- */
103
- function resolveGrantPolicy(repoPol, owner) {
104
- const o = owner || null;
105
- const ownerSet = !!(o && o.read === 'ok' && o.set);
106
- const ownerBits = ownerSet ? { owner: o.owner || null, ownerBy: o.by || null, ownerAt: o.at || null } : { owner: null, ownerBy: null, ownerAt: null };
107
- if (repoPol.declared) {
108
- const optedOut = repoPol.valid && repoPol.policy === 'human' && ownerSet && o.value === 'reviewer';
109
- return { ...repoPol, source: 'repo', optedOut, ...ownerBits, ownerNote: '',
110
- reason: optedOut
111
- ? `this repo opted out: project.yml declares migration-grant: human, which wins over the owner-level reviewer value (set by ${o.by} at ${o.at})`
112
- : repoPol.reason };
113
- }
114
- if (ownerSet) {
115
- return { policy: o.value, declared: false, valid: true, source: 'owner', optedOut: false, ...ownerBits, ownerNote: '',
116
- reason: `owner-level migration-grant: ${o.value} (set on ${o.owner || 'the owner'}/${RECORD_REPO} by ${o.by} at ${o.at}; this repo declares no key of its own)` };
117
- }
118
- const ownerNote = o && o.read === 'unread' ? `the owner-level record could not be read (${o.why || 'unknown error'}) — read as unset` : '';
119
- return { ...repoPol, source: 'default', optedOut: false, ...ownerBits, ownerNote,
120
- reason: ownerNote ? `${repoPol.reason}; ${ownerNote}` : repoPol.reason };
121
- }
122
-
123
- /** One-line source label for a printed policy: `repo`, `owner (<by> at <at>)`, or `default`. */
124
- function sourceLabel(res) {
125
- if (!res) return 'default';
126
- if (res.source === 'owner') return `owner (${res.ownerBy || '?'} at ${res.ownerAt || '?'})`;
127
- return res.source;
128
- }
129
-
130
104
  module.exports = {
131
105
  LABEL, RECORD_REPO, ISSUE_TITLE, KEYS, VALUES, UNSET, OWNER_ASSOCIATIONS, MARK_RE,
132
- isValidValue, markerBody, normComment, ownerValue, resolveGrantPolicy, sourceLabel,
106
+ isValidValue, markerBody, normComment, ownerValue,
107
+ // #598: resolveGrantPolicy / sourceLabel moved to grant-policy.js and are deliberately NOT
108
+ // re-exported: an owner record has the same { read, set, value } shape as a machine record, so a
109
+ // caller still passing one would silently get it honoured as a machine value. Fail loudly instead.
133
110
  };
@@ -171,4 +171,42 @@ function syncMergeChain(run, head, baseRef, maxDepth = 50) {
171
171
  return chain;
172
172
  }
173
173
 
174
- module.exports = { parseHandoffUrl, namesBranch, namedShas, handoffVerdict, handoffTrailer, syncMergeChain };
174
+ /**
175
+ * #591 — `--batch b1,b2@<handoff-url>`: split the batch list into member branch names and, for the
176
+ * members built on another machine, the hand-off each one names. One list, one source: the `@` rides
177
+ * the member it belongs to, so the hand-off cannot drift from the member list the way a second
178
+ * `--handoffs` map could. Each entry splits on its FIRST `@` — a §4 branch name never holds one, and
179
+ * a hand-off URL never holds a `,`. The URL itself is judged later by handoffVerdict, exactly as a
180
+ * single `--handoff` is, so a malformed one is refused with today's message, not a new one.
181
+ * Returns { members: [branch…] (deduped, in order), handoffs: { [branch]: url }, errors: [msg…] }.
182
+ */
183
+ function parseBatchEntries(list) {
184
+ const members = [];
185
+ const handoffs = {};
186
+ const errors = [];
187
+ for (const raw of String(list || '').split(',').map((x) => x.trim()).filter(Boolean)) {
188
+ const at = raw.indexOf('@');
189
+ const branch = (at < 0 ? raw : raw.slice(0, at)).trim();
190
+ const url = at < 0 ? '' : raw.slice(at + 1).trim();
191
+ if (!branch) { errors.push(`"${raw}" names a hand-off but no branch — write <branch>@<hand-off-url>`); continue; }
192
+ if (at >= 0 && !url) { errors.push(`"${raw}" has an @ but no hand-off URL after it`); continue; }
193
+ if (url) {
194
+ if (handoffs[branch] && handoffs[branch] !== url) { errors.push(`${branch} is named with two different hand-offs (${handoffs[branch]}, ${url})`); continue; }
195
+ handoffs[branch] = url;
196
+ }
197
+ if (!members.includes(branch)) members.push(branch);
198
+ }
199
+ return { members, handoffs, errors };
200
+ }
201
+
202
+ /**
203
+ * #591 — read a `Colab-Handoff:` trailer back off a squash commit body (handoffTrailer's inverse):
204
+ * `{ url, handedOff }` or null. A batch lands in a second call, so the member's door is read from
205
+ * the commit the combined run graded, never re-supplied on the command line.
206
+ */
207
+ function parseHandoffTrailer(body) {
208
+ const m = String(body || '').match(/^Colab-Handoff: (\S+) @ ([0-9a-f]{7,40})\b/m);
209
+ return m ? { url: m[1], handedOff: m[2] } : null;
210
+ }
211
+
212
+ module.exports = { parseHandoffUrl, namesBranch, namedShas, handoffVerdict, handoffTrailer, syncMergeChain, parseBatchEntries, parseHandoffTrailer };