@futurelastic/colab-handbook 1.13.0 → 1.14.0-rc.10

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.
Files changed (44) hide show
  1. package/README.md +2 -2
  2. package/README.vi.md +2 -2
  3. package/audit/audit.mjs +218 -53
  4. package/package.json +1 -1
  5. package/templates/README.md +18 -3
  6. package/templates/ci-laravel.yml +360 -40
  7. package/templates/ci-node.yml +491 -35
  8. package/templates/ci-python.yml +301 -32
  9. package/templates/deploy-container-run.mjs +17 -3
  10. package/templates/deploy-xserver.yml +12 -0
  11. package/templates/instruction-files.yml +16 -0
  12. package/templates/pre-commit-instruction-files +55 -0
  13. package/templates/release-auto.yml +16 -3
  14. package/tools/colab +884 -98
  15. package/tools/lib/adopt.js +1 -1
  16. package/tools/lib/audit-cache.js +277 -0
  17. package/tools/lib/batch-stats.js +66 -43
  18. package/tools/lib/ci-cure.js +10 -1
  19. package/tools/lib/claim-comments.js +3 -2
  20. package/tools/lib/codec/decision.d.ts +7 -0
  21. package/tools/lib/codec/decision.js +54 -0
  22. package/tools/lib/codec/hold.d.ts +8 -1
  23. package/tools/lib/codec/hold.js +42 -8
  24. package/tools/lib/codec/release.js +6 -3
  25. package/tools/lib/codec/samples.json +45 -0
  26. package/tools/lib/config-set.js +4 -3
  27. package/tools/lib/cure-diff.js +27 -1
  28. package/tools/lib/decision-record.js +42 -0
  29. package/tools/lib/docs-only.js +47 -0
  30. package/tools/lib/git.js +57 -8
  31. package/tools/lib/grant-policy.js +133 -0
  32. package/tools/lib/instruction-file.js +75 -0
  33. package/tools/lib/instruction-gate.js +179 -0
  34. package/tools/lib/landed-prs.js +58 -0
  35. package/tools/lib/migration-grant.js +29 -5
  36. package/tools/lib/owner-policy.js +110 -0
  37. package/tools/lib/release-cut.js +127 -10
  38. package/tools/lib/release-finalize.js +66 -5
  39. package/tools/lib/ship-batch.js +188 -14
  40. package/tools/lib/ship-handoff.js +212 -0
  41. package/tools/lib/stamp.js +6 -2
  42. package/tools/lib/template-trunk.js +80 -0
  43. package/tools/lib/tree-green.js +21 -4
  44. package/tools/lib/workflow-triggers.js +57 -0
package/tools/colab CHANGED
@@ -43,6 +43,8 @@ const decisionRecord = require('./lib/decision-record');
43
43
  const blockedBy = require('./lib/blocked-by');
44
44
  const ciGrant = require('./lib/ci-grant');
45
45
  const trustHumans = require('./lib/trust-humans');
46
+ const ownerPolicy = require('./lib/owner-policy');
47
+ const grantPolicy = require('./lib/grant-policy');
46
48
  const ciCure = require('./lib/ci-cure');
47
49
  const ciVerdict = require('./lib/ci-verdict');
48
50
  const baseCiVerdict = require('./lib/base-ci-verdict');
@@ -77,11 +79,15 @@ const releaseCut = require('./lib/release-cut');
77
79
  const releaseFinalize = require('./lib/release-finalize');
78
80
  const releaseChannel = require('./lib/release-channel');
79
81
  const shippedBranch = require('./lib/shipped-branch');
82
+ const landedPrs = require('./lib/landed-prs');
80
83
  const shipRoles = require('./lib/ship-roles'); // #372
84
+ const shipHandoff = require('./lib/ship-handoff'); // #578
81
85
  const refsBrake = require('./lib/refs-brake'); // #385
82
86
  const localAdopt = require('./lib/local-adopt'); // #393
83
87
  const ownerBranch = require('./lib/owner-branch'); // #394
84
88
  const humanDoor = require('./lib/ship-human-door'); // #525
89
+ const instructionGate = require('./lib/instruction-gate'); // #588
90
+ const instructionFile = require('./lib/instruction-file'); // #602
85
91
  const {
86
92
  HOST, UserError, normIssueNum, issueTag, claimKey, today, nowISO, hoursSince, humanAge,
87
93
  parseArgs, table, shortRepo,
@@ -1331,6 +1337,18 @@ Refuses, naming each failed condition (all are reported, not just the first):
1331
1337
  There the bump reads the promoted commits (main's merge subject is skipped),
1332
1338
  and a switch-removal child counts when its Closes #N was promoted.
1333
1339
 
1340
+ Route library-fast (#590) — a library released per merge, its consumers pin; nothing deploys:
1341
+ once a first final exists (a human tags it), cut tags the next FINAL vX.Y.Z directly — no
1342
+ candidate, no test period — by hand or with --auto, publishes it as the latest GitHub Release and
1343
+ moves the stable channel. --json says final: true, deploy: null. In place of already-candidate:
1344
+ already-final main's head already carries a final — a NO-OP under --auto
1345
+ release-hold an open issue carries the release-hold label (a human veto)
1346
+ With release.version-source: manifest (the route's default) the version IS the manifest's: equal
1347
+ to the last final is a NO-OP (nothing to release until a merge bumps it), lower refuses, 0.x -> 1.0
1348
+ refuses (a human tags it), a major needs MIGRATION.md's section, and a breaking change the
1349
+ manifest under-declares refuses. --bump has nothing to override there. With version-source: tag
1350
+ the bump is computed exactly as for a candidate.
1351
+
1334
1352
  Route deploy-tag-fast (#446) — a deploy: tag repo with the operator's grant and a declared health gate:
1335
1353
  --auto tags the FINAL vX.Y.Z on main's green head — no candidate, no test period — publishes it as
1336
1354
  the latest GitHub Release, moves the stable channel, and prints final/deploy in --json so the
@@ -1678,11 +1696,23 @@ function cmdReleaseCut(argv) {
1678
1696
  const fast = releaseCut.isFastRoute(policy) && !policy.findings.length;
1679
1697
  const fastFacts = fast ? measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: migrationPathsSince }) : {};
1680
1698
  if (fast && auto) auto.spacing = fastFacts.spacing;
1699
+ // #590: route library-fast — a final with nothing deployed. The release-hold veto is its one extra
1700
+ // read; a hand cut also needs MIGRATION.md for a manifest-declared major (--auto reads it already).
1701
+ const library = !fast && releaseCut.isLibraryRoute(policy) && !policy.findings.length;
1702
+ let libraryMigration = null;
1703
+ if (library) {
1704
+ fastFacts.holds = releaseCut.holdsVerdict(issues);
1705
+ if (!auto) {
1706
+ const r = git.git(['show', `${sha}:${releaseCut.MIGRATION_FILE}`], repoAbs);
1707
+ const text = r.ok ? r.stdout : null;
1708
+ libraryMigration = (v) => releaseCut.parseMigrationSection(text, v);
1709
+ }
1710
+ }
1681
1711
 
1682
1712
  const verdict = releaseCut.decide({
1683
1713
  policy, triggers, lastFinal, suggestion, tags, tagsAtSha, ci, suite, schema, switches, manifests, ancestry, auto,
1684
1714
  override: opts.bump ? { bump: opts.bump, reason: opts.reason } : null,
1685
- finalGrant: fastFacts.finalGrant, holds: fastFacts.holds, migrations: fastFacts.migrations,
1715
+ finalGrant: fastFacts.finalGrant, holds: fastFacts.holds, migrations: fastFacts.migrations, migration: libraryMigration,
1686
1716
  trackingIssue: fastFacts.tracking ? fastFacts.tracking.number : null,
1687
1717
  });
1688
1718
 
@@ -1712,6 +1742,11 @@ function cmdReleaseCut(argv) {
1712
1742
  // on the version's tracking issue (opened if there is none), for a human to grant.
1713
1743
  let announced = null;
1714
1744
  let handoff = verdict.handoff || null;
1745
+ if (library && !opts.dry && created) {
1746
+ // #590: every issue a library final carries hears which version has it, as on deploy-tag-fast.
1747
+ const exclude = (issues || []).filter((i) => releaseFinalize.parseReleaseMarker(i.body)).map((i) => i.number);
1748
+ announced = announceCarried(repoAbs, { tagNames: [...tags, verdict.tag], exclude, version: verdict.tag, sha });
1749
+ }
1715
1750
  if (fast && !opts.dry) {
1716
1751
  if (created) {
1717
1752
  const exclude = (issues || []).filter((i) => releaseFinalize.parseReleaseMarker(i.body)).map((i) => i.number);
@@ -1741,10 +1776,11 @@ function cmdReleaseCut(argv) {
1741
1776
  repo: shortRepo(repoAbs), sha, ...(offTrunk ? { trunk } : {}), lastFinal, suggestion, dry: !!opts.dry, auto: !!opts.auto,
1742
1777
  ok: verdict.ok, noop: !!verdict.noop, standing: verdict.standing || [], tag: verdict.tag, created, published, channel, version: verdict.version, bump: verdict.bump,
1743
1778
  overridden: verdict.overridden, signals: verdict.signals ? verdict.signals.lines : null, checks: verdict.checks,
1744
- // #446: present on every route, so the workflow reads one shape — final only on deploy-tag-fast.
1745
- final: !!verdict.final,
1779
+ // #446: present on every route, so the workflow reads one shape — final on deploy-tag-fast and
1780
+ // library-fast (#590); deploy only on deploy-tag-fast, so the workflow deploys nothing a library tags.
1781
+ final: !!verdict.final, route: verdict.route || null,
1746
1782
  deploy: verdict.final && verdict.healthGate ? { healthUrl: verdict.healthGate.url, rollback: verdict.healthGate.rollback } : null,
1747
- grant: verdict.grant || null, handoff, ...(fast ? { announced } : {}),
1783
+ grant: verdict.grant || null, handoff, ...(fast || library ? { announced } : {}),
1748
1784
  }, null, 2));
1749
1785
  return verdict.ok || verdict.noop ? 0 : 1;
1750
1786
  }
@@ -1760,6 +1796,8 @@ function cmdReleaseCut(argv) {
1760
1796
  if (verdict.noop) {
1761
1797
  print(fast
1762
1798
  ? '· no-op — nothing owed, inside release.final-spacing, or main\'s head already carries a final; nothing tagged.'
1799
+ : library
1800
+ ? '· no-op — nothing owed (the manifest still says the last final), or main\'s head already carries a final; nothing tagged.'
1763
1801
  : '· no-op — nothing owed, inside the route\'s cadence window, or main\'s head is not a promotion of trunk; nothing cut.');
1764
1802
  return 0;
1765
1803
  }
@@ -1770,7 +1808,15 @@ function cmdReleaseCut(argv) {
1770
1808
  if (handoff) print(`\nA migration rides this release. The one command, for a human to run:\n ${handoff}`);
1771
1809
  return 1;
1772
1810
  }
1773
- if (verdict.final) {
1811
+ if (verdict.final && library) {
1812
+ if (opts.dry) print(`[--dry] would tag the final ${verdict.tag} on ${at}, push it to ${remote}, publish its GitHub Release and move the stable channel — route library-fast, nothing deploys. Nothing created.`);
1813
+ else {
1814
+ print(`✓ tagged the final ${verdict.tag} on ${at} and pushed it to ${remote} — route library-fast: a library released per merge, nothing deploys from it.`);
1815
+ if (published && published.ok) print(`✓ ${published.detail}`);
1816
+ else if (published) warn(`${published.detail} — the tag stands; publish it by hand: gh release create ${verdict.tag} --verify-tag --latest`);
1817
+ if (announced && announced.issues.length) print(`released in ${verdict.tag}: told ${announced.posted.length ? announced.posted.map((n) => `#${n}`).join(', ') : 'nobody new'}`);
1818
+ }
1819
+ } else if (verdict.final) {
1774
1820
  if (opts.dry) print(`[--dry] would tag the final ${verdict.tag} on ${at}, push it to ${remote}, publish its GitHub Release and move the stable channel — the workflow's deploy job would then deploy it and check ${verdict.healthGate.url}. Nothing created.`);
1775
1821
  else {
1776
1822
  print(`✓ tagged the final ${verdict.tag} on ${at} and pushed it to ${remote} — route deploy-tag-fast, by the operator's grant (decision #${verdict.grant.issue}); the release workflow deploys it in this run.`);
@@ -2001,7 +2047,7 @@ function cmdReleaseFinalize(argv) {
2001
2047
  const issues = readAllIssuesForSwitches(repoAbs);
2002
2048
  const labelNames = (i) => (i.labels || []).map((l) => (typeof l === 'string' ? l : l.name));
2003
2049
  const records = (issues || [])
2004
- .map((i) => ({ number: i.number, url: i.url || null, state: String(i.state || '').toUpperCase(), createdAt: i.createdAt || null, held: labelNames(i).includes(releaseFinalize.HOLD_LABEL), version: releaseFinalize.parseReleaseMarker(i.body) }))
2050
+ .map((i) => ({ number: i.number, url: i.url || null, title: i.title == null ? null : String(i.title), state: String(i.state || '').toUpperCase(), createdAt: i.createdAt || null, held: labelNames(i).includes(releaseFinalize.HOLD_LABEL), version: releaseFinalize.parseReleaseMarker(i.body) }))
2005
2051
  .filter((r) => r.version);
2006
2052
  const trackingFor = (version, { isCandidate }) => {
2007
2053
  if (issues === null) return { error: 'the issue list could not be read (or may be truncated) — the tracking issue cannot be found' };
@@ -2009,7 +2055,7 @@ function cmdReleaseFinalize(argv) {
2009
2055
  const open = mine.filter((r) => r.state === 'OPEN');
2010
2056
  if (open.length > 1) return { error: `${open.length} open tracking issues for ${version} (${open.map((r) => `#${r.number}`).join(', ')}) — one per version; close the duplicate by hand` };
2011
2057
  if (open.length === 1) return { ...open[0] };
2012
- if (isCandidate && mine.length) return { error: `the tracking issue for ${version} (#${mine[0].number}) is closed but ${version} is not final — reopen it; a closed record is never silently replaced` };
2058
+ if (isCandidate && mine.length) return { error: `the tracking issue for ${version} (#${mine[0].number}${mine[0].title ? ` ${JSON.stringify(mine[0].title)}` : ''}) is closed but ${version} is not final — reopen it; a closed record is never silently replaced` };
2013
2059
  return { number: null, createdAt: null, held: false, wouldCreate: !opts.dry };
2014
2060
  };
2015
2061
  const version0 = newest ? newest.version : (selection.version || null);
@@ -2021,7 +2067,7 @@ function cmdReleaseFinalize(argv) {
2021
2067
  const body = releaseFinalize.trackingBody({ version: version0, row: policy.derived.row, final: policy.effective.final, testPeriodDays: policy.effective.testPeriodDays });
2022
2068
  const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(version0), body });
2023
2069
  if (!c.number) trackings.set(version0, { error: `could not open the tracking issue for ${version0} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'})` });
2024
- else { trackings.set(version0, { number: c.number, url: c.url, createdAt: now, held: false }); trackingCreated = true; }
2070
+ else { trackings.set(version0, { number: c.number, url: c.url, title: releaseFinalize.trackingTitle(version0), createdAt: now, held: false }); trackingCreated = true; }
2025
2071
  }
2026
2072
 
2027
2073
  // #441: an operator-granted automatic final — the decision it names is resolved once per run, from
@@ -2048,10 +2094,25 @@ function cmdReleaseFinalize(argv) {
2048
2094
  });
2049
2095
  // #566: only the run that CUT the candidate vouches for what it published — read from the rows
2050
2096
  // BEFORE the #425 own-workflow filter (the release workflow is the cutter), minus this run itself.
2051
- const cutRun = releaseFinalize.cutRunVerdict(rawRows, {
2097
+ const cutRunOpts = {
2052
2098
  tag: cand.tag, cutAt: cand.cutAt, ownRunId: process.env.GITHUB_ACTIONS === 'true' ? process.env.GITHUB_RUN_ID || null : null,
2053
2099
  jobCount: (id) => git.ghRunJobCount(repoAbs, id),
2054
- });
2100
+ };
2101
+ const cutRun = releaseFinalize.cutRunVerdict(rawRows, cutRunOpts);
2102
+ // #565: a run that failed only in its deploy jobs (staging) — the three run-reading conditions
2103
+ // re-read with it counted as passed. decide() uses that reading on a human final only, and names
2104
+ // the failure either way. Jobs are read lazily: only when a condition already failed.
2105
+ let deployReport = null;
2106
+ if (Array.isArray(rawRows) && !(conditions.ci.ok && conditions.suite.ok && cutRun.ok)) {
2107
+ const d = releaseFinalize.deployOnlyFailures(rawRows, (id) => git.ghRunJobs(repoAbs, id));
2108
+ if (d.failures.length) {
2109
+ const at = `${cand.tag}@${shortSha(cand.sha)}`;
2110
+ const lenRows = releaseCut.withoutOwnWorkflow(d.rows); // #425, as readRuns does
2111
+ const run = git.summarizeRunsForCommit(lenRows, cand.sha);
2112
+ const ci = run ? (({ ok, detail }) => ({ ok, detail }))(classifyCiRun(repoAbs, run, at)) : { ok: false, detail: `gh run list failed — cannot confirm CI at ${at}` };
2113
+ deployReport = { failures: d.failures, ci, suite: releaseCut.fullSuiteVerdict(lenRows, at), cutRun: releaseFinalize.cutRunVerdict(d.rows, cutRunOpts) };
2114
+ }
2115
+ }
2055
2116
  const suiteWorkflows = [...new Set((rows || []).map((r) => r.workflowName || '(unnamed workflow)'))];
2056
2117
  const period = releaseFinalize.periodVerdict({ cutAt: cand.cutAt, trackingCreatedAt: tracking && tracking.createdAt, testPeriodDays: policy.effective.testPeriodDays, now });
2057
2118
  // #437: the window is main plus project.yml's trunk: when that is another branch (trunk: dev).
@@ -2075,7 +2136,7 @@ function cmdReleaseFinalize(argv) {
2075
2136
  }
2076
2137
  const verdict = releaseFinalize.decide({
2077
2138
  policy, selection: sel, tracking, supersededHeld, period, trunk, regressions,
2078
- ci: conditions.ci, suite: conditions.suite, cutRun, schema: conditions.schema, switches: conditions.switches,
2139
+ ci: conditions.ci, suite: conditions.suite, cutRun, deployReport, schema: conditions.schema, switches: conditions.switches,
2079
2140
  manifests, ancestry, tags: tagNames, finalGrant, migrations,
2080
2141
  human: { bar: humanBar, answeredBy: opts.answeredBy || null },
2081
2142
  });
@@ -2202,7 +2263,7 @@ function cmdReleaseFinalize(argv) {
2202
2263
 
2203
2264
  const supersededHeld = records.filter((r) => r.state === 'OPEN' && r.held && r.version !== (cand ? cand.version : version0) && !finals.has(r.version)).map((r) => r.number);
2204
2265
  const trackingOut = tracking && !tracking.error
2205
- ? { number: tracking.number || null, url: tracking.url || null, created: trackingCreated && (!cand || cand.version === version0), held: !!tracking.held, supersededHeld }
2266
+ ? { number: tracking.number || null, url: tracking.url || null, title: tracking.title || null, created: trackingCreated && (!cand || cand.version === version0), held: !!tracking.held, supersededHeld }
2206
2267
  : null;
2207
2268
  // #468: why this run made no final, and which candidate finals first — the line the release
2208
2269
  // workflow prints, so "no final" never has to be reconstructed from a checklist.
@@ -3792,7 +3853,8 @@ It is minted only when ALL of these hold, checked before any network call:
3792
3853
  - the record is well-formed AND passing (approve · checklist pass · escalation clear · CI pass) —
3793
3854
  a grant carrying a failing review is a contradiction, so it is refused, not recorded;
3794
3855
  - the branch is pushed, and --head (if given) equals origin's tip — the grant binds that tip;
3795
- - this checkout's project.yml declares \`migration-grant: reviewer\` (#398; absent = human);
3856
+ - the policy resolves to \`reviewer\` (#598): this checkout's project.yml \`migration-grant:\` when
3857
+ declared (#398), else this machine's value (\`colab config set migration-grant\`), else human;
3796
3858
  - checklist-items, when given, is <passed>/${migrationGrant.REVIEW_CHECKLIST_ITEMS} and, with checklist pass, every item
3797
3859
  passed (#457) — the record counts against the checklist the migration-review skill walks today.
3798
3860
  Then, read from CI after the tracker read and before anything is written (#457):
@@ -3800,8 +3862,8 @@ Then, read from CI after the tracker read and before anything is written (#457):
3800
3862
  passed there (the rule ship applies), and --ci-run, when given, is one of the runs at that
3801
3863
  head and carries the job. A repo whose CI has no such job cannot mint a reviewer grant at all.
3802
3864
  COLAB_HUMAN=1 is still required for every role. The reviewer identity is DECLARED, not attested.
3803
- \`colab ship\` honours a reviewer grant only when ALL of (#401): P the target's project.yml says
3804
- \`migration-grant: reviewer\` · M this record is live, trusted and passing · HEAD its head is the
3865
+ \`colab ship\` honours a reviewer grant only when ALL of (#401): P the policy at the target resolves to
3866
+ 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
3805
3867
  branch's exact remote head, or its \`migrations\` id equals the id at that head · R the live
3806
3868
  "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job passed on the SHIPPED head (re-read by ship, never
3807
3869
  taken from the record). Any condition failing → a human runs Phase B.
@@ -3906,11 +3968,19 @@ function migrationGrantReviewRecord(repoAbs, opts) {
3906
3968
 
3907
3969
  // Policy first: under the default (human) a reviewer grant would do nothing and mislead. Read from
3908
3970
  // THIS checkout (trunk at rest), never the branch — a branch must not raise its own grant policy.
3909
- const pol = migrationGrant.parseGrantPolicy(projectDoc(repoAbs));
3971
+ // #598: three levels — this checkout's key > this machine's value > human (grant-policy.js).
3972
+ const pol = migrationGrantPolicyFor(projectDoc(repoAbs));
3910
3973
  if (!pol.valid) throw new UserError(`${pol.reason} — fix project.yml before minting a reviewer grant`);
3911
3974
  if (pol.policy !== 'reviewer') {
3975
+ if (pol.optedOut) {
3976
+ 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
+ }
3978
+ if (pol.machineNote) {
3979
+ 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
+ }
3912
3981
  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`);
3913
3982
  }
3983
+ opts.policyResolved = pol;
3914
3984
 
3915
3985
  // HEAD binding: the grant covers exactly the commit on origin. An unpushed branch has no tip any
3916
3986
  // other machine can check against, so it is refused rather than bound to a local-only sha.
@@ -4041,6 +4111,7 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
4041
4111
  print(' Bound to that HEAD: any new commit voids it. It expires the moment the issue closes.');
4042
4112
  }
4043
4113
  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 === 'machine') print(` Policy source: ${opts.policyResolved.reason}.`);
4044
4115
  print(` Revoke any time: colab migration-grant ${num} --revoke`);
4045
4116
  return 0;
4046
4117
  }
@@ -4113,9 +4184,15 @@ function cmdMigrationGrantList(opts) {
4113
4184
  grants.push(row);
4114
4185
  }
4115
4186
 
4187
+ // #598: the policy these grants are judged under, with its source (repo | machine | default).
4188
+ const pol = migrationGrantPolicyFor(projectDoc(repoAbs));
4189
+ const policy = { value: pol.policy, source: pol.source, optedOut: pol.optedOut,
4190
+ ...(pol.source === 'machine' ? { by: pol.machineBy, at: pol.machineAt, host: pol.machineHost } : {}) };
4116
4191
  if (opts.json) {
4117
- return print(JSON.stringify({ repo: shortRepo(repoAbs), label: labels.MIGRATION_GRANT_LABEL, grants, stale }, null, 2));
4192
+ return print(JSON.stringify({ repo: shortRepo(repoAbs), label: labels.MIGRATION_GRANT_LABEL, policy, grants, stale }, null, 2));
4118
4193
  }
4194
+ // Prose names the source only where the machine level is in play — otherwise byte-identical.
4195
+ if (pol.source === 'machine' || pol.optedOut || pol.machineNote) print(`migration-grant policy: ${pol.policy} (source: ${grantPolicy.sourceLabel(pol)}) — ${pol.reason}`);
4119
4196
 
4120
4197
  if (grants.length === 0 && stale.length === 0) {
4121
4198
  print(`no outstanding migration grants in ${shortRepo(repoAbs)}`);
@@ -4132,6 +4209,118 @@ function cmdMigrationGrantList(opts) {
4132
4209
  return 0;
4133
4210
  }
4134
4211
 
4212
+ // ---------------------------------------------------------------------------
4213
+ // owner-policy (#596) — RETIRED as a resolution rung by #598. `show` still reads the owner record,
4214
+ // read-only, and says it is not honoured; `set` refuses. The policy resolves repo key > this
4215
+ // machine's value > human (tools/lib/grant-policy.js; `colab config set migration-grant`).
4216
+
4217
+ const HELP_OWNER_POLICY = `colab owner-policy [show] [--json] [--repo <path>]
4218
+
4219
+ The owner-level grant policy (#596) is RETIRED (#598). No gate reads it. It was a marker comment
4220
+ on the open \`${ownerPolicy.LABEL}\`-labelled issue in <owner>/${ownerPolicy.RECORD_REPO}, accepted from any
4221
+ owner or org MEMBER — and the shared account agent sessions post from is typically a member, so one
4222
+ raw API call (which no COLAB_HUMAN bar can see) switched reviewer grants on for every repo.
4223
+
4224
+ The policy now resolves, everywhere (\`colab migration-grant\` when minting and listing, \`colab ship\`):
4225
+ 1. the repo's own \`migration-grant:\` in project.yml — \`human\` there opts the repo out
4226
+ 2. this MACHINE's value: COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>
4227
+ 3. the default, \`human\`
4228
+
4229
+ show print any owner value still standing (marked: not honoured) and what THIS repo resolves
4230
+ to now, with its source (repo | machine | default)
4231
+ set refused, always — set this machine's value instead (above)
4232
+ `;
4233
+
4234
+ /** The `<owner>/.github` REST paths, with gh's {owner} placeholder — resolved from the repo's remote. */
4235
+ function ownerRecordPath(rest) { return `repos/{owner}/${ownerPolicy.RECORD_REPO}/${rest}`; }
4236
+
4237
+ function ghFirstLine(s) { return String(s || '').trim().split('\n')[0] || 'gh failed'; }
4238
+
4239
+ /**
4240
+ * Locate the owner record issue. Returns { read: 'ok', issue, owner } · { read: 'none', owner? }
4241
+ * (no .github repo, or no labelled open issue — "nothing set", never an error) · { read: 'unread', why }.
4242
+ */
4243
+ function ownerRecordIssue(repoAbs) {
4244
+ const r = git.ghApi(repoAbs, [ownerRecordPath(`issues?labels=${ownerPolicy.LABEL}&state=open&per_page=100`)]);
4245
+ if (!r.ok) {
4246
+ if (/HTTP 404|Not Found/i.test(r.stderr || '')) return { read: 'none', owner: null, why: `no ${ownerPolicy.RECORD_REPO} repo for this owner` };
4247
+ return { read: 'unread', why: ghFirstLine(r.stderr) };
4248
+ }
4249
+ let list;
4250
+ try { list = JSON.parse(r.stdout); } catch (_) { return { read: 'unread', why: 'unparseable issue list' }; }
4251
+ const issues = (Array.isArray(list) ? list : []).filter((i) => i && !i.pull_request).sort((a, b) => a.number - b.number);
4252
+ if (issues.length === 0) return { read: 'none', owner: null, why: `no open ${ownerPolicy.LABEL} issue` };
4253
+ const m = String(issues[0].repository_url || '').match(/\/repos\/([^/]+)\//);
4254
+ return { read: 'ok', issue: issues[0].number, owner: m ? m[1] : null };
4255
+ }
4256
+
4257
+ /**
4258
+ * #596: the owner-level value for `key`, judged with the reading repo's `trust`. Returns the shape
4259
+ * owner-policy.js resolveGrantPolicy takes: { read, owner, issue, set, value, by, at, ignored, why }.
4260
+ */
4261
+ function ownerPolicyRead(repoAbs, trust, key = 'migration-grant') {
4262
+ const loc = ownerRecordIssue(repoAbs);
4263
+ if (loc.read !== 'ok') return { ...loc, set: false, value: null, ignored: [] };
4264
+ const c = git.ghApi(repoAbs, ['--paginate', ownerRecordPath(`issues/${loc.issue}/comments?per_page=100`),
4265
+ '--jq', '.[] | {user: {login: .user.login}, author_association, created_at, body}']);
4266
+ if (!c.ok) return { read: 'unread', why: ghFirstLine(c.stderr), set: false, value: null, ignored: [] };
4267
+ const comments = [];
4268
+ for (const line of c.stdout.split('\n')) {
4269
+ if (!line.trim()) continue;
4270
+ try { comments.push(JSON.parse(line)); } catch (_) { return { read: 'unread', why: 'unparseable comment list', set: false, value: null, ignored: [] }; }
4271
+ }
4272
+ return { read: 'ok', owner: loc.owner, issue: loc.issue, ...ownerPolicy.ownerValue(comments, key, trust) };
4273
+ }
4274
+
4275
+ /**
4276
+ * #598: the migration-grant policy for a repo — repo key > this machine's value > human. `doc` is
4277
+ * the project.yml that counts (the trunk checkout for a mint, the merge target for ship). The SAME
4278
+ * exported function a console imports (grant-policy.js effectiveGrantPolicy), so they cannot differ.
4279
+ * The owner-level record (#596) is not read here: retired as a rung.
4280
+ */
4281
+ function migrationGrantPolicyFor(doc) {
4282
+ return grantPolicy.effectiveGrantPolicy(doc);
4283
+ }
4284
+
4285
+ function cmdOwnerPolicy(argv) {
4286
+ const opts = parseArgs(argv, {
4287
+ values: { '--repo': 'repo' },
4288
+ flags: { '--json': 'json', '-h': 'help', '--help': 'help' },
4289
+ });
4290
+ if (opts.help) return print(HELP_OWNER_POLICY);
4291
+ const sub = opts._[0] || 'show';
4292
+ if (sub === 'set') {
4293
+ // #598: retired. Refused whether or not COLAB_HUMAN is set — nothing is read or posted.
4294
+ process.stderr.write('✗ Refusing: the owner-level grant policy is retired (#598) — no gate reads it, so setting it would do nothing.\n');
4295
+ process.stderr.write(' Set this machine\'s value instead: COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>\n');
4296
+ return 1;
4297
+ }
4298
+ if (sub !== 'show') throw new UserError(`unknown owner-policy subcommand "${sub}" — expected one of show | set`);
4299
+ const repoAbs = resolveRepoOrCwd(opts);
4300
+ if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4301
+ if (!isGhUsable(repoAbs)) throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — the owner policy lives on the tracker`);
4302
+ const doc = projectDoc(repoAbs);
4303
+ const trust = trustHumans.parseTrustHumans(doc);
4304
+ const owner = ownerPolicyRead(repoAbs, trust);
4305
+ const res = migrationGrantPolicyFor(doc);
4306
+ const out = {
4307
+ repo: shortRepo(repoAbs),
4308
+ owner: { retired: true, read: owner.read, owner: owner.owner || null, issue: owner.issue || null, why: owner.why || null,
4309
+ 'migration-grant': owner.set ? { value: owner.value, by: owner.by, at: owner.at } : null, ignored: owner.ignored || [] },
4310
+ resolved: { 'migration-grant': { policy: res.policy, source: res.source, valid: res.valid, optedOut: res.optedOut, reason: res.reason } },
4311
+ };
4312
+ if (opts.json) return print(JSON.stringify(out, null, 2));
4313
+ const where = owner.owner ? `${owner.owner}/${ownerPolicy.RECORD_REPO}#${owner.issue}` : `<owner>/${ownerPolicy.RECORD_REPO}`;
4314
+ if (owner.read === 'unread') warn(`could not read the owner record (${owner.why}) — read as unset`);
4315
+ 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`);
4316
+ for (const i of owner.ignored || []) warn(`ignored marker ${i.value} by ${i.login || '(unknown)'} at ${i.at}: ${i.reason}`);
4317
+ print(`${shortRepo(repoAbs)} resolves to: ${res.policy} (source: ${grantPolicy.sourceLabel(res)}) — ${res.reason}`);
4318
+ if (owner.set && owner.value === 'reviewer' && res.source === 'default') {
4319
+ 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');
4320
+ }
4321
+ return 0;
4322
+ }
4323
+
4135
4324
  // ---------------------------------------------------------------------------
4136
4325
  // decision (#121, #122) — record a human's answer to a blocking `needs-decision` question as a
4137
4326
  // POSITIVE, machine-readable act, never as the label's mere absence. See tools/lib/decision-
@@ -4169,8 +4358,14 @@ TRUSTED_ASSOCIATIONS, checked on read. Same principle, a different mechanism, be
4169
4358
  command TRANSCRIBES a decision made elsewhere rather than AUTHORIZING a write that did not exist
4170
4359
  before it ran — the flag would assert nothing here that \`--ruled-by\` does not already.
4171
4360
 
4172
- \`--answers <ref>\` names the \`<!-- decision:options -->\` comment (id or URL) this decision
4173
- resolves, when one exists — omit it when there was no options block.
4361
+ \`--answers <ref>\` names the question this decision resolves: an ASK ID (the \`id=\` of an open
4362
+ \`<!-- <tool>:ask id=<id> v=<n> -->\` record a dashboard that tracks asks wrote on the issue), or the
4363
+ \`<!-- decision:options -->\` comment (id or URL). Omit it only when there is neither. --record
4364
+ reads the issue's open asks first (#582) — an ask with no answer record, and no ⚖ record
4365
+ naming it, after its latest version: with ONE open ask and no --answers it prints the ask id
4366
+ and the exact re-run line, and says the ruling will be read as answering that ask; with TWO OR
4367
+ MORE it REFUSES before any write and lists every id, because a nameless ruling cannot say which
4368
+ one it settles.
4174
4369
 
4175
4370
  Reopening removes \`${labels.DECISION_RECORDED_LABEL}\`, re-applies \`${labels.NEEDS_DECISION_LABEL}\`,
4176
4371
  and posts a \`${decisionRecord.REOPEN_MARK}\` receipt — every decision on that issue up to this
@@ -4199,7 +4394,7 @@ Options:
4199
4394
  and an issue number is present, for the common one-shot case)
4200
4395
  --reopen reopen an existing decision instead of recording a new one
4201
4396
  --ruled-by <name> required for --record/--reopen — who made this call, never the typist
4202
- --answers <ref> (--record only) the decision:options comment this answers, if any
4397
+ --answers <ref> (--record only) the open ask id, or the decision:options comment, this answers
4203
4398
  --body-file <f> ruling prose (or reopen reason) to append below the marker line
4204
4399
  --list list every issue with a live decision right now, instead of recording
4205
4400
  --json (with --list) machine-readable output
@@ -4291,6 +4486,23 @@ function cmdDecisionRecord(repoAbs, num, opts, body) {
4291
4486
  ${pair.fix}`);
4292
4487
  }
4293
4488
 
4489
+ // #582: show the recorder the asks still waiting on this issue, so the ruling names the one it
4490
+ // settles. One open ask + no --answers: a consumer reads the ruling as answering it — say so.
4491
+ // Two or more + no --answers: ambiguous, refuse before any write (same posture as the pair
4492
+ // check above) and list the ids.
4493
+ const asks = decisionRecord.openAsks(info.comments);
4494
+ const shellQuote = (v) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(String(v)) ? String(v) : `'${String(v).replace(/'/g, `'\\''`)}'`);
4495
+ if (asks.length > 0 && !opts.answers) {
4496
+ const rerun = (id) => `colab decision ${num} --record --ruled-by ${shellQuote(opts.ruledBy)} --answers ${shellQuote(id)}${opts.bodyFile ? ` --body-file ${shellQuote(opts.bodyFile)}` : ''}`;
4497
+ const rows = asks.map((a) => ` ${a.id} (v${a.version}, asked ${a.at || 'unknown'})\n ${rerun(a.id)}`).join('\n');
4498
+ if (asks.length > 1) {
4499
+ throw new UserError(`#${num} has ${asks.length} open asks and this record names none — a reader cannot tell which one the ruling settles. Re-run with --answers <ask id>:
4500
+ ${rows}`);
4501
+ }
4502
+ warn(`#${num} has one open ask: ${asks[0].id} (v${asks[0].version}, asked ${asks[0].at || 'unknown'}). This ruling will be read as answering it. To name it explicitly, re-run as:
4503
+ ${rerun(asks[0].id)}`);
4504
+ }
4505
+
4294
4506
  const present = git.ghListLabels(repoAbs);
4295
4507
  if (present && !present.includes(labels.DECISION_RECORDED_LABEL)) {
4296
4508
  throw new UserError(labels.decisionRecordedMissingLabelHint(present)
@@ -4474,7 +4686,8 @@ CI grant merges into a repo whose own test suite is known-failing:
4474
4686
  for the BRANCH's own current head (the same "ask by sha" check \`ship\` itself uses) — a human's
4475
4687
  say-so alone is never enough. \`--evidence-run\` is a RECORDING-ONLY pointer for the audit trail;
4476
4688
  it can never substitute for the measured run. If the branch has no run yet, open a PR for it
4477
- (\`gh pr create\`) and let CI finish, then re-run this command.
4689
+ (\`gh pr create\`) and let CI finish, then re-run this command. You do not need to close that
4690
+ PR afterwards: \`colab ship\` closes it once the branch lands (#584).
4478
4691
  2. NEVER STACKS. Creating a grant refuses outright if trunk is not currently red (nothing to
4479
4692
  exempt), and refuses again if a PRIOR ci-grant already merged something and trunk has been red
4480
4693
  continuously since — a second exemption on a still-broken repo is exactly the failure this gate
@@ -4823,7 +5036,7 @@ function cmdCiGrantCreate(repoAbs, num, opts) {
4823
5036
  throw new UserError(
4824
5037
  `"${opts.branch}" has no completed, successful CI run for its current head (${shortSha(evRun.sha)}) — ` +
4825
5038
  `a CI grant requires MEASURED evidence, never a human's say-so alone. Open a PR for it ` +
4826
- `(\`gh pr create\`) and let CI finish, then re-run this command.`);
5039
+ `(\`gh pr create\`) and let CI finish, then re-run this command — \`colab ship\` closes that PR once the branch lands (#584).`);
4827
5040
  }
4828
5041
  const evidenceSha = evRun.sha;
4829
5042
 
@@ -6290,6 +6503,9 @@ in a cleanup cron.
6290
6503
  reported but never deleted (a label a triage session just created and has not
6291
6504
  applied yet is indistinguishable from one whose members were all transferred
6292
6505
  away — the labels API exposes no creation time, so a human decides).
6506
+ Also lists open PRs whose head commit already landed in trunk (#584) — CI-trigger
6507
+ PRs a squash ship left open. Report-only, --prune included: doctor never closes
6508
+ a PR. A PR whose head is not in the local clone is not judged.
6293
6509
  `;
6294
6510
 
6295
6511
  const EMPTY_SET = new Set();
@@ -6374,7 +6590,7 @@ function cmdDoctor(argv) {
6374
6590
  const report = { deadWorktrees: [], orphanClaims: [], staleClaims: [], stalePlaces: [], unprovablePlaces: [], releasedPlaces: [], orphanPorts: [], brokenRecords: [], prunedPorts: [],
6375
6591
  renamedHostRecords: [], unprovenHostRecords: [],
6376
6592
  mergedFlips: [], mergedSweep: [], mergedDirty: [], mergedHookFail: [], mergedRemoveFail: [], shippedBranches: [], ghostPorts: [],
6377
- spentGroupLabels: [], groupLabelsChecked: !!opts.sync, pruned: !!opts.prune };
6593
+ spentGroupLabels: [], groupLabelsChecked: !!opts.sync, landedPrs: [], landedPrsUnread: [], pruned: !!opts.prune };
6378
6594
 
6379
6595
  // One answer per (repo, branch) — pass 5b asks about the same branch from a worktree and from each
6380
6596
  // of its claims, and every miss costs two `git rev-parse` calls.
@@ -6765,6 +6981,28 @@ function cmdDoctor(argv) {
6765
6981
  }
6766
6982
  }
6767
6983
 
6984
+ // 9b. open PRs whose head already landed (#584) — the CI-trigger PRs a squash ship left open before
6985
+ // ship learned to close them, or that a ship on another machine could not close. Report-only,
6986
+ // --prune included: closing a PR is a write on a shared forge, and a human may still want it.
6987
+ // Behind --sync for the same reason as pass 9 (network). A PR whose head commit is not in this
6988
+ // clone is not judged — the answer would be a guess — so the list is honest, not exhaustive.
6989
+ if (opts.sync && git.ghAvailable()) {
6990
+ const repos = [...new Set([...(config.repos || []), ...knownRepos(config)].map((r) => path.resolve(r)))]
6991
+ .filter((r) => repoLive(r) && git.remoteUrl(r));
6992
+ for (const repo of repos) {
6993
+ const trunk = resolveTrunk(repo, projectDoc(repo));
6994
+ if (!trunk) continue;
6995
+ const listed = git.ghOpenPrs(repo);
6996
+ if (listed.error) { report.landedPrsUnread.push({ repo: shortRepo(repo), error: listed.error }); continue; }
6997
+ for (const pr of listed.prs) {
6998
+ if (!pr.headRefOid || pr.headRefName === trunk) continue;
6999
+ if (!git.git(['cat-file', '-e', `${pr.headRefOid}^{commit}`], repo).ok) continue;
7000
+ if (landed.landedState(repo, trunk, pr.headRefOid).state !== 'landed') continue;
7001
+ report.landedPrs.push({ repo: shortRepo(repo), number: pr.number, url: pr.url || '', branch: pr.headRefName || '', trunk });
7002
+ }
7003
+ }
7004
+ }
7005
+
6768
7006
  // 10. notifyUrl against a DECLARED local observer (#414). Read-only, never pruned, never counted in
6769
7007
  // the verdict — it is configuration, not state drift. Silent on a machine with no
6770
7008
  // <COLAB_HOME>/notify-endpoint: unset is the right default where no observer runs.
@@ -6914,6 +7152,17 @@ function cmdDoctor(argv) {
6914
7152
  print(' NOT exhaustive: a branch whose work trunk later rewrote can conflict against trunk');
6915
7153
  print(' instead of matching it, and is omitted here rather than risk calling unmerged work spent.');
6916
7154
  }
7155
+ // #584 — after the verdict, not counted: an open PR on a landed branch breaks nothing, it reads as
7156
+ // unmerged work on a tracker. Printed only under --sync.
7157
+ if (report.landedPrs.length) {
7158
+ print('');
7159
+ print(`Open PRs whose branch already landed (${report.landedPrs.length}) — the squash left them open:`);
7160
+ for (const p of report.landedPrs) print(` #${p.number} ${p.branch} [${p.repo}] → in ${p.trunk}${p.url ? ` ${p.url}` : ''}`);
7161
+ print(' `colab ship` closes these itself since #584; these predate that, or a ship could not close them.');
7162
+ print(' doctor never closes a PR, --prune included. To close one:');
7163
+ print(` gh pr close ${report.landedPrs[0].number} --comment "Landed on ${report.landedPrs[0].trunk} by squash." # in ${report.landedPrs[0].repo}`);
7164
+ }
7165
+ for (const u of report.landedPrsUnread) warn(`could not list open PRs in ${u.repo} (${u.error}) — landed-PR check skipped there`);
6917
7166
  // Also after the verdict, and also not drift: a spent group label breaks nothing, it is picker
6918
7167
  // noise on a tracker. Printed only under --sync, so silence here NEVER means "checked, clean" —
6919
7168
  // which is why a --sync run that finds nothing says so explicitly below.
@@ -7681,6 +7930,11 @@ const HELP_CONFIG = `colab config [show|add-repo <path>|rm-repo <path>|add-reser
7681
7930
  rm-notify-url <url> remove one receiver from notifyUrl; removing the last unsets the key
7682
7931
  set <key> <value> set claimTTLHours | plannerClaimTTLMinutes | portRange | worktreeSubdir | notifyUrl | journal |
7683
7932
  claimIdentity
7933
+ set migration-grant <human|reviewer|unset> [--by <name>]
7934
+ this MACHINE's migration-grant policy (#598) — HUMAN-ONLY, refused without
7935
+ COLAB_HUMAN=1; records who, when, host and machine. Repos that declare
7936
+ their own migration-grant: win; repos without one resolve to this value,
7937
+ else human. Not the repo's key — that stays an authority key (below).
7684
7938
  set <tuning-key> <value> --evidence "<why>"
7685
7939
  a kebab-case key is this REPO's .github/project.yml, not this machine (#561):
7686
7940
  one tuning value, committed on a short branch, shippable with no issue —
@@ -7731,6 +7985,7 @@ asserted — and, like docs-only (#345), it opens the autonomy gate on a repo wi
7731
7985
  Every other precondition still applies.
7732
7986
 
7733
7987
  Never on this path (they grant authority or change what deploys): ${configSet.AUTHORITY_KEYS.join(', ')}.
7988
+ (\`colab config set migration-grant <v>\` is a different command: THIS MACHINE's value, human-only, #598.)
7734
7989
 
7735
7990
  --evidence <text> the measurement behind the number (required)
7736
7991
  --no-push create the branch locally only
@@ -7797,13 +8052,52 @@ function cmdConfigSetDescriptor(argv) {
7797
8052
  return 0;
7798
8053
  }
7799
8054
 
8055
+ /**
8056
+ * #598: `config set migration-grant <human|reviewer|unset>` — THIS MACHINE's migration-grant
8057
+ * policy, stored in config.json `policy["migration-grant"]` (tools/lib/grant-policy.js). Routed here
8058
+ * before the descriptor path: there `migration-grant` is an authority key and is refused, so the
8059
+ * command had no meaning until now. HUMAN-ONLY, checked first — before any argument is parsed.
8060
+ */
8061
+ function cmdConfigSetMachinePolicy(argv) {
8062
+ if (process.env.COLAB_HUMAN !== '1') {
8063
+ process.stderr.write('✗ Refusing: setting the machine-level migration-grant policy requires a human.\n');
8064
+ 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');
8065
+ return 1;
8066
+ }
8067
+ const opts = parseArgs(argv, {
8068
+ values: { '--by': 'by', '--repo': 'repo', '--evidence': 'evidence' },
8069
+ flags: { '--dry': 'dry', '--no-push': 'noPush' },
8070
+ });
8071
+ if (opts.repo || opts.evidence || opts.dry || opts.noPush) {
8072
+ 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');
8073
+ }
8074
+ const value = opts._[1]; // opts._[0] is migration-grant — cmdConfig routes here on exactly that key
8075
+ const allowed = [...grantPolicy.VALUES, grantPolicy.UNSET];
8076
+ if (!allowed.includes(value)) throw new UserError(`config set migration-grant: value ${JSON.stringify(value)} — expected one of ${allowed.join(' | ')}`);
8077
+ let by = opts.by;
8078
+ if (!by) { try { by = os.userInfo().username; } catch (_) { by = null; } }
8079
+ const iso = nowISO();
8080
+ const meta = { by: by || null, at: iso, host: os.hostname(), machine: myMachineId() };
8081
+ state.saveConfig(grantPolicy.withValue(state.loadConfig(), value, meta));
8082
+ if (value === grantPolicy.UNSET) {
8083
+ print('migration-grant (machine) = (unset) — repos without their own key fall back to human');
8084
+ } else {
8085
+ print(`migration-grant (machine) = ${value} — set by ${meta.by || '?'} at ${iso} on ${meta.host}`);
8086
+ print(' Repos that declare their own migration-grant: are unaffected; migration-grant: human in a repo opts it out. Check: colab migration-grant --list');
8087
+ }
8088
+ return 0;
8089
+ }
8090
+
7800
8091
  function cmdConfig(argv) {
7801
8092
  const sub = argv[0];
8093
+ if (sub === 'set' && argv[1] === grantPolicy.MACHINE_KEY) return cmdConfigSetMachinePolicy(argv.slice(1)); // #598, human gate first
7802
8094
  const cfg = state.loadConfig();
7803
8095
  if (!sub || sub === 'show') {
7804
8096
  print(`state: ${state.STATE_FILE}`);
7805
8097
  print(`config: ${state.CONFIG_FILE}`);
7806
8098
  print(JSON.stringify(cfg, null, 2));
8099
+ const mp = grantPolicy.readMachinePolicy();
8100
+ 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}`}`);
7807
8101
  const reserved = ports.reservedSet(cfg, knownRepos(cfg));
7808
8102
  print(`reserved ports (${reserved.size}): ${[...reserved.keys()].sort((a, b) => a - b).join(', ') || '—'}`);
7809
8103
  return 0;
@@ -9022,6 +9316,13 @@ async function cmdAdopt(argv) {
9022
9316
  : `detected (the repo's default branch, ${nowDate})`;
9023
9317
  entries.push({ key: 'trunk', value: extra.trunk, comment: `# trunk: ${trunkNote}` });
9024
9318
  }
9319
+ // #602: on a fork, the instruction-file check cannot see the `upstream` remote in CI — so the
9320
+ // fork verdict above (adoptDetectFork, the one fork test) is recorded as the key CI reads.
9321
+ // Detected, never asked, like trunk and stack; never written over an existing declaration.
9322
+ if (extra.fork && !(instructionFile.INSTRUCTION_FILES_KEY in cfg)) {
9323
+ entries.push({ key: instructionFile.INSTRUCTION_FILES_KEY, value: 'upstream',
9324
+ comment: `# instruction-files: detected — a fork (${extra.fork.source === 'flag' ? '--fork' : `remote "${extra.fork.remote}"`}, ${nowDate}); CLAUDE.md/AGENTS.md are the upstream's, so the instruction-file check leaves them unjudged (CONVENTIONS.md §9, #602)` });
9325
+ }
9025
9326
  if (!('stack' in cfg)) {
9026
9327
  if (opts.stack !== undefined) {
9027
9328
  const stackNote = stackAnsweredInteractively
@@ -9302,6 +9603,10 @@ prepended at the top for a *.yml/*.yaml copy, since there is no shebang to prote
9302
9603
  opens with a \`#!\` shebang (a *.mjs template) gets the same stamp on its SECOND line instead —
9303
9604
  using \`//\` there, since a bare \`#\` on any other line is a JS syntax error — so the shebang
9304
9605
  still has to be line 1 for the file to run.
9606
+ A ci-* template is also written with this repo's protected refs (#526): the template names
9607
+ \`main\`/\`dev\` in concurrency and the dedupe guard; the copy names the \`trunk:\` declared in
9608
+ .github/project.yml (plus \`main\` where a promotion into main releases), and says what it wrote.
9609
+ It then lists the repo's other workflows that also run on push, for you to keep, merge or delete.
9305
9610
  These templates are NEVER called remotely — copy, edit, own. When the audit flags your
9306
9611
  copy as behind a changed template, review the diff and re-copy to re-stamp.
9307
9612
  `;
@@ -9391,7 +9696,30 @@ function cmdTemplate(argv) {
9391
9696
  warn('handbook has no tags yet — stamping @ v0. Tag the handbook, then re-copy to stamp a real version.');
9392
9697
  }
9393
9698
 
9394
- const body = fs.readFileSync(srcFile, 'utf8');
9699
+ let body = fs.readFileSync(srcFile, 'utf8');
9700
+ // #526: a CI template names its protected refs `main`/`dev` — defaults, not this repo's facts.
9701
+ // Write the repo's declared trunk (and release branch) instead, and say what changed.
9702
+ const trunkNotes = [];
9703
+ let repoForCopy = null;
9704
+ if (ext === 'yml') {
9705
+ try { repoForCopy = git.repoRoot(path.dirname(destFile)) || resolveWorkingRepo(opts); } catch (_) { repoForCopy = null; }
9706
+ }
9707
+ if (ext === 'yml' && /^ci-/.test(stem)) {
9708
+ const tt = require('./lib/template-trunk');
9709
+ let doc = null;
9710
+ if (repoForCopy) doc = repoDescriptorDoc(repoForCopy);
9711
+ const p = tt.protectedRefs(doc);
9712
+ if (!p) {
9713
+ trunkNotes.push(' trunk: no `trunk:` in .github/project.yml — the template\'s main/dev refs are left as is; walk its # EDIT: markers.');
9714
+ } else {
9715
+ const r = tt.substituteTrunk(body, p);
9716
+ body = r.text;
9717
+ trunkNotes.push(r.changes.length
9718
+ ? ` trunk: wrote ${p.refs.join(', ')} (from .github/project.yml) into: ${r.changes.join(', ')}.`
9719
+ : ` trunk: ${p.refs.join(', ')} — the template's refs already match .github/project.yml.`);
9720
+ if (r.missed.length) trunkNotes.push(` ⚠ trunk: not found in this template, check by hand: ${r.missed.join(', ')}.`);
9721
+ }
9722
+ }
9395
9723
  // A *.yml copy has no shebang to protect, so this is still a plain prepend at line 1 — unchanged
9396
9724
  // from before. A *.mjs copy opens with `#!/usr/bin/env node`; insertStamp puts the stamp on line
9397
9725
  // 2 instead so the shebang stays first and the file keeps running as a script (#252).
@@ -9405,6 +9733,23 @@ function cmdTemplate(argv) {
9405
9733
  // extension) is exactly how a stem collision reads back as a false confirmation (#252).
9406
9734
  print(`✓ ${stem}.${ext} @ ${version} → ${destFile}`);
9407
9735
  print(' stamped. Walk its # EDIT: markers, declare your toolchain, then commit. You own this file now.');
9736
+ for (const l of trunkNotes) print(l);
9737
+ // #526: a repo adopting a CI template usually has CI already. Both then run on every push —
9738
+ // name them and leave the choice to the person, never decide it here.
9739
+ if (ext === 'yml' && /^ci-/.test(stem) && repoForCopy) {
9740
+ const wfDir = path.join(repoForCopy, '.github', 'workflows');
9741
+ let others = [];
9742
+ try {
9743
+ const wt = require('./lib/workflow-triggers');
9744
+ others = fs.readdirSync(wfDir)
9745
+ .filter((f) => /\.ya?ml$/.test(f) && path.join(wfDir, f) !== destFile)
9746
+ .filter((f) => { const on = wt.parseWorkflowOn(fs.readFileSync(path.join(wfDir, f), 'utf8')); return on.found && on.events.has('push'); });
9747
+ } catch (_) { others = []; }
9748
+ if (others.length) {
9749
+ print(' Other workflows here also run on push — keep each, merge it into this one, or delete it (your call):');
9750
+ for (const f of others) print(` .github/workflows/${f}`);
9751
+ }
9752
+ }
9408
9753
  return 0;
9409
9754
  }
9410
9755
 
@@ -9475,6 +9820,8 @@ function inspectRepo(entry, ctx) {
9475
9820
  try { wfs = fs.existsSync(wfDir) ? fs.readdirSync(wfDir).filter((f) => /\.ya?ml$/.test(f)).sort() : []; }
9476
9821
  catch (_) { wfs = []; }
9477
9822
 
9823
+ // #526: a CI copy is written with this repo's refs, so pristine means "as colab template renders it here".
9824
+ const descDoc = repoDescriptorDoc(abs);
9478
9825
  for (const wf of wfs) {
9479
9826
  const rel = `.github/workflows/${wf}`;
9480
9827
  const text = read(rel);
@@ -9483,6 +9830,7 @@ function inspectRepo(entry, ctx) {
9483
9830
  const c = stamp.classifyStamped({
9484
9831
  root: ctx.handbookRoot, hb: ctx.hb, tmplNames: ctx.tmplNames,
9485
9832
  templateName: st.name, stampVersion: st.version, localText: text, comparable: true,
9833
+ render: (body) => require('./lib/template-trunk').renderForRepo(st.name, body, descDoc),
9486
9834
  });
9487
9835
  artifacts.push({ file: rel, template: st.name, applicable: c.state === 'behind', ...c });
9488
9836
  } else {
@@ -9566,10 +9914,17 @@ function entryLabel(entry) {
9566
9914
  }
9567
9915
 
9568
9916
  /** Rewrite a behind-but-pristine workflow copy as the current template, freshly stamped. */
9917
+ /** A repo's parsed .github/project.yml, or null when absent or unreadable. */
9918
+ function repoDescriptorDoc(repoAbs) {
9919
+ try { return require('./lib/yaml').parse(fs.readFileSync(path.join(repoAbs, '.github', 'project.yml'), 'utf8')) || {}; }
9920
+ catch (_) { return null; }
9921
+ }
9922
+
9569
9923
  function refreshArtifact(repo, art, ctx) {
9570
9924
  const src = path.join(ctx.templatesDir, `${art.template}.yml`);
9571
9925
  if (!fs.existsSync(src)) return { ok: false, err: `template ${art.template}.yml is not in the handbook` };
9572
- const body = fs.readFileSync(src, 'utf8');
9926
+ // Rendered exactly as `colab template <name> --force` would write it here (#526).
9927
+ const body = require('./lib/template-trunk').renderForRepo(art.template, fs.readFileSync(src, 'utf8'), repoDescriptorDoc(repo.path));
9573
9928
  const dest = path.join(repo.path, art.file);
9574
9929
  try {
9575
9930
  fs.mkdirSync(path.dirname(dest), { recursive: true });
@@ -10027,7 +10382,10 @@ function shipMigrationGate(repoAbs, gh, target, branch, issues) {
10027
10382
  /** P, HEAD and the R thunk for shipMigrationGate. The thunk memoises its one verdict on the ctx
10028
10383
  * (`roundtripResult`) so the payload can report what R saw without a second read. */
10029
10384
  function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
10030
- const policy = migrationGrant.parseGrantPolicy(projectDocAt(repoAbs, target)).policy;
10385
+ // #598: the target's key > this machine's value > human.
10386
+ const trust = trustAt(repoAbs, target);
10387
+ const pres = migrationGrantPolicyFor(projectDocAt(repoAbs, target));
10388
+ const policy = pres.policy;
10031
10389
  const remote = git.remoteInfo(repoAbs).name || 'origin';
10032
10390
  const ls = git.git(['ls-remote', remote, `refs/heads/${branch}`], repoAbs);
10033
10391
  const remoteSha = ls.ok ? ((ls.stdout.split('\n')[0] || '').split('\t')[0].trim() || null) : null;
@@ -10037,10 +10395,12 @@ function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
10037
10395
  if (!remoteSha) headNote = `${branch} could not be read on ${remote} — CI cannot have run a HEAD nobody can see`;
10038
10396
  else if (localSha && localSha !== remoteSha) headNote = `local ${branch} is ${localSha.slice(0, 7)}, ${remote} is ${remoteSha.slice(0, 7)} — push or pull until they agree`;
10039
10397
  else headSha = remoteSha;
10040
- const trust = trustAt(repoAbs, target);
10041
10398
  // #508: what the branch's migration files ARE at the shipped head, for a content-bound grant.
10042
10399
  const contentId = headSha ? migrationContentAt(repoAbs, migrations, headSha) : null;
10043
10400
  const ctx = { policy, headSha, contentId, headNote, roundtripResult: null, trust,
10401
+ policySource: pres.source, policyRes: pres,
10402
+ // Only where the machine level is in play: the default/repo refusal text stays byte-identical.
10403
+ policyReason: pres.source === 'machine' || pres.optedOut || pres.machineNote ? pres.reason : null,
10044
10404
  labelActors: (n) => git.ghIssueLabelActors(repoAbs, n, labels.MIGRATION_GRANT_LABEL) };
10045
10405
  ctx.roundtrip = () => {
10046
10406
  const d = git.git(['diff', '--name-only', `${target}...${branch}`], repoAbs);
@@ -10073,6 +10433,12 @@ function migDetail(migrations, grants, target, branch, ctx) {
10073
10433
  const payload = {
10074
10434
  branch, files: [...migrations],
10075
10435
  policy: ctx ? ctx.policy : null,
10436
+ // #598: where the policy came from — repo | machine | default — and, for machine, who set it when.
10437
+ policySource: ctx ? ctx.policySource || null : null,
10438
+ // #596's field, kept for additive-only consumers: always null now that the owner level is retired.
10439
+ policyOwner: null,
10440
+ policyMachine: ctx && ctx.policyRes && ctx.policyRes.source === 'machine'
10441
+ ? { by: ctx.policyRes.machineBy, at: ctx.policyRes.machineAt, host: ctx.policyRes.machineHost } : null,
10076
10442
  headSha: ctx ? ctx.headSha : null,
10077
10443
  contentId: ctx ? ctx.contentId || null : null,
10078
10444
  // #407: the human list as read from the TARGET — null when undeclared (association class).
@@ -10086,7 +10452,9 @@ function migDetail(migrations, grants, target, branch, ctx) {
10086
10452
  if (grants.ok) {
10087
10453
  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(' ');
10088
10454
  const roles = [...new Set(grants.granted.map((g) => g.role || 'human'))].join('+');
10089
- return { text: `${migrations.length} present, exempted by a ${roles} grant on ${by} for branch "${branch}" — ${files}`, payload };
10455
+ const src = ctx && ctx.policySource === 'machine' && grants.granted.some((g) => g.role === 'reviewer')
10456
+ ? ` (policy: ${grantPolicy.sourceLabel(ctx.policyRes)})` : '';
10457
+ return { text: `${migrations.length} present, exempted by a ${roles} grant on ${by} for branch "${branch}"${src} — ${files}`, payload };
10090
10458
  }
10091
10459
  // Each missing entry already carries its own specific, actionable reason (evaluateShipSet) —
10092
10460
  // report those verbatim rather than just an issue tag, so an operator or a scheduled driver's
@@ -10124,7 +10492,12 @@ function migDetail(migrations, grants, target, branch, ctx) {
10124
10492
  * from its base. An empty result is now left empty; the caller decides what to say about it
10125
10493
  * (buildSquashMessage below), rather than this layer inventing a commit to hide it.
10126
10494
  */
10127
- function branchCommits(mainRoot, trunk, branch) {
10495
+ function branchCommits(mainRoot, trunk, branchName) {
10496
+ // #603: read the branch through the ref it resolves to. A hand-off branch (or any --branch with no
10497
+ // local ref) is remote-only on the lander, and a bare name does not DWIM to refs/remotes/<remote>/
10498
+ // — the log failed, the list came back empty, and the squash subject read "(none …)" on a branch
10499
+ // that has commits. shipRefFor is local || remote || the name itself, so a sha passes unchanged.
10500
+ const branch = shipRefFor(mainRoot, branchName);
10128
10501
  const mb = git.git(['merge-base', trunk, branch], mainRoot);
10129
10502
  const base = mb.ok && mb.stdout ? mb.stdout : trunk;
10130
10503
  const logShas = git.git(['log', '--first-parent', `${base}..${branch}`, '--no-merges', '--format=%H'], mainRoot);
@@ -10148,7 +10521,7 @@ function commitFiles(mainRoot, sha) {
10148
10521
 
10149
10522
  /** Files the whole branch changed against its base — the denominator for the same signal. */
10150
10523
  function branchChangedFiles(mainRoot, base, branch) {
10151
- const r = git.git(['diff', '--name-only', `${base}...${branch}`], mainRoot);
10524
+ const r = git.git(['diff', '--name-only', `${base}...${shipRefFor(mainRoot, branch)}`], mainRoot); // #603: same remote-only gap
10152
10525
  return r.ok ? r.stdout.split('\n').map((s) => s.trim()).filter(Boolean) : [];
10153
10526
  }
10154
10527
 
@@ -10221,8 +10594,8 @@ function ciCureTrailerLine(cureVerdict, branch, trunk) {
10221
10594
  return `CI-Cure: branch ${branch} over-red ${trunk}@${shortSha(cureVerdict.redSha)} evidence ${shortSha(cureVerdict.evidenceSha)}${via}${admittedSuffix}${progressSuffix}`;
10222
10595
  }
10223
10596
 
10224
- 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]
10225
- colab ship --batch <b1,b2[,b3]> [--repo <path>] [--keep-worktree] [--delete-branch | --keep-branch] [--session <id>] [--session-name <s>] [--dry]
10597
+ 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]
10598
+ colab ship --batch <b1,b2[@<handoff-url>][,…]> [--split] [--repo <path>] [--keep-worktree] [--delete-branch | --keep-branch] [--session <id>] [--session-name <s>] [--dry]
10226
10599
 
10227
10600
  The ONE sanctioned door for code-wrap Phase B: squash-merge a session branch into the BASE IT WAS
10228
10601
  CUT FROM — trunk for an ordinary session, or the declared integration line recorded on its worktree
@@ -10317,6 +10690,33 @@ here, or pass --adopt if it genuinely has no issue — the squash then carries a
10317
10690
  \`Colab-Adopted: origin/<br> @ <sha> on <host> (machine <id>)\` trailer. A LOCAL no-digit branch is
10318
10691
  still a legitimate zero. --adopt never bypasses a branch that names issues.
10319
10692
 
10693
+ A HAND-OFF (#578) is the non-force door for a branch whose claim lives on ANOTHER machine:
10694
+ \`colab ship --branch <br> --handoff <url>\`, where <url> is the executor's hand-off comment
10695
+ (…/issues/<N>#issuecomment-<id>). With zero claims here, ship takes the issue set from the branch
10696
+ name's trailing run once the hand-off proves all of: the comment is on one of THIS repo's issues,
10697
+ one the branch carries; it names the branch and a sha that is the remote branch's CURRENT head (a
10698
+ 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
10699
+ live \`🔒 Claimed\` comment on that branch, posted by the hand-off's author before it. Nothing is
10700
+ claimed or taken over here: the executor keeps its claim, worktree and branch until it confirms
10701
+ the land, the shipped branch is kept, the squash carries \`Colab-Handoff: <url> @ <sha>\`, and each
10702
+ 🚢 comment names the hand-off. Any check failing refuses (exit 1); --force is never involved, and
10703
+ the human takeover (\`colab claim --force\`) stays the only other way in. Not with --adopt
10704
+ or --direct, and not when this machine already holds a claim on the branch.
10705
+
10706
+ IN A BATCH (#591) the hand-off rides its member: \`--batch b1,b2@<url>\` (split on the first @).
10707
+ That member is verified by this SAME door — same checks, same refusal text, which drops it from
10708
+ the batch while the rest build — then joins the combined run with no sync of its own; its squash
10709
+ carries the Colab-Handoff trailer, and the land reads the door back from that commit. Repeat the
10710
+ same list, @ included, on every call: a rebuild re-verifies its members from the command line.
10711
+ A bare --handoff beside --batch names no member and refuses.
10712
+
10713
+ A remote-built branch that fell BEHIND its base (#579) is synced by the lander as usual (B0: merge
10714
+ the base in, push) — and the hand-off still verifies, because the commits between the handed-off
10715
+ sha and the new head are each a PURE base-sync merge: two parents, the second already on the base,
10716
+ and a tree equal to git's own conflict-free merge of the two. A fix-up, a rebase, or a merge whose
10717
+ conflict was resolved by hand is not one, and still needs a new hand-off from the executor. The
10718
+ trailer then reads \`Colab-Handoff: <url> @ <handed-off sha> (synced to <head> by N base merge(s))\`.
10719
+
10320
10720
  UNATTACHED CLAIMS (#319). A claim taken with no --worktree and no --branch (\`colab claim <N>
10321
10721
  --session <id>\`) is carried by a branch ship only when BOTH hold: its session equals this ship's
10322
10722
  (--session / COLAB_SESSION, or the worktree record's), and the branch name's trailing group names
@@ -10421,7 +10821,7 @@ Every other precondition is unchanged. No flag, env var or project.yml field wid
10421
10821
 
10422
10822
  TUNING-ONLY — the second computed exception (#561). Ship also proceeds without the grant when the
10423
10823
  diff changes .github/project.yml ALONE, every changed line inside a tuning key (ship-batch,
10424
- ship-batch-wait, ci-wait-factor, thresholds) and every moved value valid; never with an authority
10824
+ ship-batch-wait, ship-batch-steps, ci-wait-factor, thresholds) and every moved value valid; never with an authority
10425
10825
  key (autonomy, promotion, migration-grant, ci-grant, trust-humans, exposure, tier, trunk, deploy,
10426
10826
  release, production). It needs no issue. \`colab config set <key> <value> --evidence "<why>"\`
10427
10827
  writes such a branch. The row reads "tuning-only (<keys>) — autonomy exception (#561)"; --dry --json
@@ -10445,9 +10845,11 @@ keeps its claim so a re-run finds it. Cannot be combined with --worktree/--branc
10445
10845
  --delete-branch/--keep-branch/--keep-worktree/--adopt. \`writes: direct\` is not required. --dry and --dry --json
10446
10846
  work as usual (json: \`direct: true\`, \`branch: null\`, \`mode: "evidence-close"\`, \`coreReview\`).
10447
10847
 
10448
- BATCH LANDING (--batch, #373) — opt-in per repo: \`ship-batch: <N>\` in project.yml, an integer 1–3;
10848
+ BATCH LANDING (--batch, #373) — opt-in per repo: \`ship-batch: <N>\` in project.yml, an integer 1–${shipBatch.MAX_BATCH};
10449
10849
  absent or 1 declines every --batch call. It tests up to N green candidates as ONE combined head, then
10450
- fast-forwards trunk, so a queue of green work stops draining at one change per trunk-CI cycle:
10850
+ fast-forwards trunk, so a queue of green work stops draining at one change per trunk-CI cycle.
10851
+ A batch of ONE is valid (#562): a lone ready member lands the same way, so the combined run — the
10852
+ setups a repo runs only on ship-batch/** and trunk — gates it too, and it needs no sync + re-run:
10451
10853
  - each member must be green at its OWN head (or have no run that could ever arrive), pass every
10452
10854
  gate its own \`ship --dry --json\` reports, and be an ordinary squash into trunk through the
10453
10855
  auto-trunk grant — the docs-only door, a migration, a ci-grant/cure, a core-path review, an
@@ -10465,15 +10867,24 @@ It never waits: each call reads the remote, takes ONE step and exits —
10465
10867
  it, bounded (code-ship B1a), and run the SAME command again
10466
10868
  4 declined — nothing landed; the last line is "→ SERIAL: colab ship --branch <b1> · …". Causes:
10467
10869
  not enabled, no auto-trunk, no workflow fires on ship-batch/** (the run could never arrive),
10468
- trunk CI red (the cure/grant doors apply per member, never to a batch), fewer than two members
10469
- can join, or the combined run is red — classify it: red:infra → the printed \`gh run rerun\`,
10470
- once; red:finding, or red again after that one re-run → serial
10870
+ trunk CI red (the cure/grant doors apply per member, never to a batch), no member can join,
10871
+ or a batch of ONE whose combined run is red — classify it: red:infra → the printed
10872
+ \`gh run rerun\`, once; red:finding, or red again after that one re-run → serial.
10873
+ A red batch of TWO OR MORE never goes serial (#557): red:infra → re-run once; red:finding →
10874
+ the same command plus --split; red again after the re-run → it splits by itself. A split
10875
+ rebuilds the same ship-batch/<trunk-sha7> with the FIRST half of its members (exit 3); the rest
10876
+ wait for the next batch, and a red half splits again
10471
10877
  1 refused (a broken checkout, an unreadable remote) — or the land push was refused while trunk did
10472
10878
  NOT move (a local pre-push hook, a remote rejection): the push's own output is echoed, and
10473
10879
  re-running hits the same refusal until its cause is fixed (#509)
10474
10880
  One batch per base: a batch at this base carrying OTHER members is waited on (exit 3) while its run
10475
10881
  is pending or green, but a declined one — its combined run red — is deleted and the batch you asked
10476
10882
  for is built in its place, so the survivors of a decline can batch without landing serially first (#391).
10883
+ The batch also holds the trunk LANE (#581): while a ship-batch/<trunk-sha7> ref at trunk's tip has its
10884
+ combined run in flight — or green within ${shipBatch.LANE_GRACE_SEC / 60}m, so its lander can land it — a serial
10885
+ \`colab ship --branch\` into trunk pauses with exit 3 (⏸ BATCH-IN-FLIGHT; its --dry --json row
10886
+ 'no batch in flight (#581)' reads self-clearing) instead of moving trunk under it and discarding the run.
10887
+ A red batch, or one with no run / not landed past that grace, holds nothing.
10477
10888
  A member that conflicts with the members already in is dropped to the next batch; the rest go on —
10478
10889
  unless every conflicting path is generated (defaults + project.yml generated:): then .colab/hooks/pre-ship
10479
10890
  regenerates them on the combined head and the member stays in (#387). No hook, or a failing one → dropped.
@@ -10483,12 +10894,17 @@ at build, added since) is NOT landed with it — the command names both lists an
10483
10894
  --dry pushes, deletes, lands, comments and releases nothing on EVERY path (#415): a fresh batch is built
10484
10895
  locally and printed; a staged green batch prints what would land (members, combined run, target sha).
10485
10896
  Consumer CI must opt in: add 'ship-batch/**' to a CI workflow's push: branches:.
10897
+ ADAPTIVE SIZE (#557) — opt-in per repo: \`ship-batch-steps: 2,4,8\` in project.yml, ascending sizes
10898
+ within ship-batch. Absent or malformed: every batch is up to ship-batch, exactly as above. With it,
10899
+ each batch head carries "Ship-Batch-Size: <s>" ("<s> red" on a split half), and the next batch is
10900
+ built at the step above the last landed one's size after a green, the step below after a red, the
10901
+ smallest step when trunk carries none yet.
10486
10902
  PARTNER WAIT (#555) — opt-in per repo: \`ship-batch-wait: <duration>\` in project.yml (90s, 6m, 1h; the
10487
10903
  unit is required). Absent, zero or malformed: no wait, exactly as above. With it, a call where exactly
10488
10904
  ONE member can join pauses (exit 3, "⏸ PARTNER-WAIT", the seconds left) until that window has passed
10489
10905
  since the member became ready (its head CI's last update, else its head commit's date) — then the same
10490
- call declines it to serial (exit 4). The caller waits, gathers every ready candidate again and calls
10491
- --batch with all of them. A single named branch is accepted only when the field is set.
10906
+ call builds it as a batch of one (#562). The caller waits, gathers every ready candidate again and
10907
+ calls --batch with all of them. Without the field, a lone member is built at once.
10492
10908
 
10493
10909
  B3 KEEPS the branch by default. Deleting refs from a shared remote is not something this command
10494
10910
  does unasked, however certain it is that the content landed: reporting is safe and reversible,
@@ -11079,6 +11495,7 @@ function treeGreenVerdict(repoAbs, run, verdict) {
11079
11495
  const ids = treeGreen.treeSkipCheckRuns(checks);
11080
11496
  if (!ids || !ids.length) return verdict;
11081
11497
  const cites = [];
11498
+ const docs = [];
11082
11499
  let unreadable = 0;
11083
11500
  const treeOf = (sha) => {
11084
11501
  const r = git.git(['rev-parse', '--verify', '--quiet', `${sha}^{tree}`], repoAbs);
@@ -11086,7 +11503,11 @@ function treeGreenVerdict(repoAbs, run, verdict) {
11086
11503
  };
11087
11504
  const ours = treeOf(run.sha);
11088
11505
  for (const id of ids) {
11089
- const cite = treeGreen.parseCitation(git.ghCheckRunAnnotations(repoAbs, id));
11506
+ const annotations = git.ghCheckRunAnnotations(repoAbs, id);
11507
+ // #570: a docs-only skip — the guard found every changed path documentation from a green base.
11508
+ const docsSkip = treeGreen.parseDocsSkip(annotations);
11509
+ if (docsSkip) { docs.push(docsSkip); continue; }
11510
+ const cite = treeGreen.parseCitation(annotations);
11090
11511
  if (!cite) { unreadable++; continue; }
11091
11512
  const theirs = treeOf(cite.head);
11092
11513
  if (ours && theirs && ours !== theirs) {
@@ -11095,7 +11516,7 @@ function treeGreenVerdict(repoAbs, run, verdict) {
11095
11516
  }
11096
11517
  cites.push({ ...cite, proof: ours && theirs ? 'verified' : 'unverified' });
11097
11518
  }
11098
- return { ...verdict, detail: verdict.detail + treeGreen.citationNote(cites, unreadable), treeGreen: cites.map((c) => c.url) };
11519
+ return { ...verdict, detail: verdict.detail + treeGreen.citationNote(cites, unreadable, docs), treeGreen: cites.map((c) => c.url) };
11099
11520
  }
11100
11521
 
11101
11522
  /**
@@ -11458,12 +11879,14 @@ function ciGrantPayload(ciResult) {
11458
11879
  * on its own.
11459
11880
  *
11460
11881
  * Measures, in order:
11461
- * 1. containment — `git merge-base --is-ancestor <redSha> <branch>`, translated to a bool.
11882
+ * 1. containment — cure-diff's `cureContainment`: `git merge-base --is-ancestor <redSha> <ref>`
11883
+ * against the ref ship lands (local branch, else `<remote>/<branch>` — #589), translated to
11884
+ * true/false, or null ("could not resolve") when the ref or the red sha does not resolve.
11462
11885
  * 2. evidence — a completed, successful CI run for `branch`'s CURRENT head, via the identical
11463
11886
  * `ghRunForSha` the raw CI check and `shipCiGrants` both use.
11464
11887
  * 3. anti-stacking — `computeAntiStacking`, the SAME function `cmdCiGrantCreate` calls, so a cure
11465
11888
  * and a human grant can never independently disagree about whether trunk is mid-stack.
11466
- * 4. the diff signals — tools/lib/cure-diff.js's `cureDiffSignals` over `<trunk>...<branch>`
11889
+ * 4. the diff signals — tools/lib/cure-diff.js's `cureDiffSignals` over `<trunk>...<ref>` (same ref)
11467
11890
  * (merge-base-relative, the tree a squash lands), `--no-renames` so a workflow file or
11468
11891
  * manifest MOVED away still counts (#297 — the old `--name-only` read listed only a rename's
11469
11892
  * new path). It yields `workflowsTouched` (condition 4) and `manifestScriptsTouched`
@@ -11499,11 +11922,17 @@ function shipCiCure(repoAbs, gh, target, trunk, redSha, branch) {
11499
11922
  if (!gh) {
11500
11923
  return { ok: false, reason: `gh not usable (${ghUnusableWhy(repoAbs)}) — the cure rule needs a measured CI run`, redSha, evidenceSha: null };
11501
11924
  }
11502
- const containsRedSha = git.git(['merge-base', '--is-ancestor', redSha, branch], repoAbs).ok;
11925
+ // #589: containment and the diff read the ref ship lands — the local branch, else its remote-tracking
11926
+ // ref (a --handoff land has no local branch). The bare name failed there and read as "not an
11927
+ // ancestor"; an unresolvable ref now refuses as "could not resolve", never as "does not contain".
11928
+ // The CI read keeps the NAME: ghRunForSha resolves the remote head itself (ls-remote).
11929
+ const containment = cureDiff.cureContainment(git, repoAbs, redSha, branch);
11930
+ const containsRedSha = containment.contains;
11931
+ const branchRef = containment.ref || branch;
11503
11932
  const evRun = git.ghRunForSha(repoAbs, branch);
11504
11933
  const evidence = !evRun ? null : { ok: evRun.status === 'completed' && evRun.conclusion === 'success', sha: evRun.sha };
11505
11934
  const stacking = computeAntiStacking(repoAbs, trunk, true /* trunkIsRed: shipCiCure is only ever reached from a HUMAN_GATED raw verdict */);
11506
- const diff = cureDiff.cureDiffSignals(git, repoAbs, trunk, branch);
11935
+ const diff = cureDiff.cureDiffSignals(git, repoAbs, trunk, branchRef);
11507
11936
  // Measured only past containment + 2a: a verdict that already refuses on either never reads it,
11508
11937
  // so a branch that cannot cure pays no job-level `gh` calls for it.
11509
11938
  const jobEvidence = (containsRedSha && evidence && evidence.ok)
@@ -11515,7 +11944,7 @@ function shipCiCure(repoAbs, gh, target, trunk, redSha, branch) {
11515
11944
  const dispatchable = jobEvidence && evidence ? dispatchableWorkflows(repoAbs, evidence.sha) : [];
11516
11945
  // #477: a stacked refusal may be lifted by progress — measure the prior red set only then.
11517
11946
  const priorRedJobs = jobEvidence && stacking && stacking.stacked ? priorExemptionRedJobs(repoAbs, trunk, stacking) : null;
11518
- const verdict = ciCure.cureVerdict({ containsRedSha, evidence, redSha, stacking, jobEvidence, priorRedJobs,
11947
+ const verdict = ciCure.cureVerdict({ containsRedSha, containmentReason: containment.reason, evidence, redSha, stacking, jobEvidence, priorRedJobs,
11519
11948
  workflowsTouched: diff.workflowsTouched,
11520
11949
  manifestScriptsTouched: diff.manifestScriptsTouched, manifestPaths: diff.manifestPaths,
11521
11950
  manifestScriptsAddOnly: diff.manifestScriptsAddOnly,
@@ -11838,8 +12267,13 @@ function cmdShipDryJson(opts) {
11838
12267
  const trunk = resolveTrunk(repoAbs, doc);
11839
12268
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
11840
12269
  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)`);
12270
+ const handoff = applyShipHandoff(repoAbs, sess, opts, trunk); // #578 — same resolution as the prose path
11841
12271
 
11842
12272
  const checks = [];
12273
+ if (handoff) {
12274
+ checks.push({ name: 'hand-off verified (#578)', ok: handoff.ok, class: handoff.ok ? null : HUMAN_GATED,
12275
+ detail: handoff.ok ? handoffDetail(handoff) : `${handoff.reason}: ${handoff.detail}` });
12276
+ }
11843
12277
  let target = null;
11844
12278
  // #74/#263: the close-gate split (closeIssues/refsIssues/checklistFindings) is reported
11845
12279
  // ALONGSIDE `checks` AS WELL AS folded into it — `closeIssues`/`refsIssues`/`checklistFindings`
@@ -11892,6 +12326,11 @@ function cmdShipDryJson(opts) {
11892
12326
  baseCi: baseCiPayloadVal, dirtyOwners: dirtyOwnersPayloadVal, autonomyGate: autonomyGatePayloadVal,
11893
12327
  coreReview: coreReviewPayloadVal,
11894
12328
  ...machineTrailerPayload(mode === 'squash' || mode === 'pr-pending'),
12329
+ // #591: the verified hand-off (or its refusal), so `ship --batch` puts this member's
12330
+ // Colab-Handoff trailer on its squash and words a refusal exactly as the single door does.
12331
+ ...(handoff ? { handoff: handoff.ok
12332
+ ? { ok: true, url: handoff.url, sha: handoff.sha, handedOff: handoff.handedOff, syncMerges: handoff.syncMerges || 0 }
12333
+ : { ok: false, reason: handoff.reason, detail: handoff.detail } } : {}),
11895
12334
  };
11896
12335
  // #373: `ship --batch` reads each member through this SAME function — handed the body, not stdout.
11897
12336
  if (opts._report) opts._report.body = body;
@@ -12053,11 +12492,14 @@ function cmdShipDryJson(opts) {
12053
12492
  // ---- (c) no hand-merge conflict — NEW: the plain --dry prose path never checks this today ----
12054
12493
  const generated = [...DEFAULT_GENERATED, ...(Array.isArray(doc.generated) ? doc.generated.map(String) : [])];
12055
12494
  const hasPreShip = fs.existsSync(path.join(repoAbs, '.colab', 'hooks', 'pre-ship'));
12056
- const mc = shipMergeConflictCheck(repoAbs, target, sess.branch, generated, hasPreShip);
12495
+ // #591: read the branch through the ref it actually resolves to — a hand-off branch is remote-only
12496
+ // here, and its bare name resolves to nothing (the same gap #589 closed for the cure rule).
12497
+ const dryShipRef = shipRefFor(repoAbs, sess.branch);
12498
+ const mc = shipMergeConflictCheck(repoAbs, target, dryShipRef, generated, hasPreShip);
12057
12499
  checks.push({ name: 'no hand-merge conflict', ok: mc.ok, class: mc.ok ? null : (mc.unknown ? SELF_CLEARING : HUMAN_GATED), detail: mc.detail });
12058
12500
 
12059
12501
  // ---- (d) the two checks the machine-facing path was missing entirely ----
12060
- const dryCommits = branchCommits(repoAbs, target, sess.branch);
12502
+ const dryCommits = branchCommits(repoAbs, target, dryShipRef);
12061
12503
 
12062
12504
  // #87: B1b's cross-check, same rule as the prose path — only over the issues that would CLOSE.
12063
12505
  const dryCorr = shipguard.corroborateIssues(closeIssues, sess.branch, dryCommits);
@@ -12100,7 +12542,7 @@ function cmdShipDryJson(opts) {
12100
12542
  // #90: "branch has commits" — the precondition whose absence told an unattended caller `ok: true`
12101
12543
  // about a branch that could not ship. It is NOT a failure when the branch qualifies for
12102
12544
  // evidence-close; it is a different mode, and saying so is the whole point.
12103
- const dryMode = shipMode(repoAbs, target, sess.branch, dryCommits);
12545
+ const dryMode = shipMode(repoAbs, target, dryShipRef, dryCommits);
12104
12546
  if (dryMode.evidenceClose) {
12105
12547
  mode = 'evidence-close';
12106
12548
  checks.push({ name: 'branch has commits', ok: true, class: null,
@@ -12114,6 +12556,17 @@ function cmdShipDryJson(opts) {
12114
12556
  if (coreReviewJson.verdict === 'pending') mode = 'pr-pending';
12115
12557
  }
12116
12558
 
12559
+ // #581: the same lane read as the prose path's table — a squash into trunk while a batch holds the
12560
+ // lane would discard the batch's run. SELF_CLEARING: the batch lands or is declined on its own.
12561
+ // Never for a batch member read (the batch IS the lane) nor for evidence-close (trunk does not move).
12562
+ if (!dryMode.evidenceClose && !opts._batchMember) {
12563
+ const laneJson = shipBatchLaneCheck(repoAbs, doc, trunk, target, gh);
12564
+ if (laneJson) {
12565
+ checks.push({ name: 'no batch in flight (#581)', ok: !laneJson.held, class: laneJson.held ? SELF_CLEARING : null,
12566
+ detail: laneJson.detail, ...(laneJson.held ? { batchRef: laneJson.ref } : {}) });
12567
+ }
12568
+ }
12569
+
12117
12570
  // #149: the same inherited-closing-keyword scan the prose --dry path runs, mirrored here —
12118
12571
  // following #153's own precedent for this function (its comment above: "a caller reading only
12119
12572
  // checks[]/ok … used to see NO check at all here"). Without this, the ONE caller class this path
@@ -12909,6 +13362,72 @@ function autonomyGatePayload(gate) {
12909
13362
  }
12910
13363
 
12911
13364
  /** The sha a branch name resolves to, local first, else origin's copy (#324's remote-only shape). */
13365
+ /**
13366
+ * #578 — `--handoff <comment-url>`: verify the executor's recorded hand-off and, when it holds, take
13367
+ * the session's issue set from it (tools/lib/ship-handoff.js says what it must prove). Returns null
13368
+ * without --handoff, the failing verdict on a refusal, the passing one after mutating `sess`.
13369
+ *
13370
+ * Writes nothing locally: no claim record, no worktree record. The executor's claim is the claim;
13371
+ * this ship only lands what it handed off, so B3 has nothing of THIS machine's to release.
13372
+ */
13373
+ function applyShipHandoff(repoAbs, sess, opts, trunk) {
13374
+ if (!opts.handoff) return null;
13375
+ 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');
13376
+ if (sess.issues.length) {
13377
+ 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(' ')} ` +
13378
+ `for ${sess.branch} — ship it without --handoff`);
13379
+ }
13380
+ const u = shipHandoff.parseHandoffUrl(opts.handoff);
13381
+ let comment = null;
13382
+ if (u) {
13383
+ const r = git.ghApi(repoAbs, [`repos/{owner}/{repo}/issues/comments/${u.commentId}`]);
13384
+ if (r.ok) {
13385
+ try {
13386
+ const j = JSON.parse(r.stdout);
13387
+ comment = { body: j.body || '', login: (j.user && j.user.login) || '', createdAt: j.created_at || '', htmlUrl: j.html_url || '' };
13388
+ } catch (_) { comment = null; }
13389
+ }
13390
+ }
13391
+ // The head check must read the remote as it is NOW, not a tracking ref from whenever this clone last fetched.
13392
+ const remote = git.remoteFor(repoAbs);
13393
+ if (u && comment) git.git(['fetch', '--quiet', remote, `+refs/heads/${sess.branch}:refs/remotes/${remote}/${sess.branch}`], repoAbs);
13394
+ const refs = git.branchRefs(repoAbs, sess.branch, remote);
13395
+ // #579: base-sync merges the lander (B0) stacked on the handed-off head do not void the hand-off.
13396
+ // Read against the base as it is NOW — the merges' second parents must already be on it.
13397
+ let syncChain = [];
13398
+ if (u && comment && refs && refs.remoteSha && trunk) {
13399
+ git.git(['fetch', '--quiet', remote, `+refs/heads/${trunk}:refs/remotes/${remote}/${trunk}`], repoAbs);
13400
+ syncChain = shipHandoff.syncMergeChain((a) => git.git(a, repoAbs), refs.remoteSha, `refs/remotes/${remote}/${trunk}`);
13401
+ }
13402
+ const claimsByIssue = {};
13403
+ if (u && comment) {
13404
+ for (const n of shipguard.branchIssueNumbers(sess.branch)) {
13405
+ const info = git.ghIssueView(repoAbs, n, ['comments']);
13406
+ claimsByIssue[n] = info ? liveClaimComments(info.comments || []).map((c) => ({ ...c })) : null;
13407
+ }
13408
+ }
13409
+ const v = shipHandoff.handoffVerdict({ url: opts.handoff, comment, branch: sess.branch, refs, claimsByIssue, syncChain });
13410
+ if (!v.ok) return v;
13411
+ sess.issues = v.issues;
13412
+ sess.handoff = v;
13413
+ // #372: the implementer is the executor that handed off — name it, never leave it reading as the shipper.
13414
+ const ex = (claimsByIssue[v.issues[0]] || []).find((c) => c.branch === sess.branch && c.login === v.executor.login);
13415
+ if (ex && (ex.session || ex.sessionName)) sess.holder = { session: ex.session || '', sessionName: ex.sessionName || '' };
13416
+ return v;
13417
+ }
13418
+
13419
+ function handoffDetail(v) {
13420
+ const head = v.syncMerges
13421
+ ? `${shortSha(v.handedOff)}, under ${v.syncMerges} clean base-sync merge${v.syncMerges === 1 ? '' : 's'} to the remote head ${shortSha(v.sha)} (#579)`
13422
+ : `${shortSha(v.sha)} = the remote head`;
13423
+ return `${v.url} hands off ${head}; executor ${v.executor.login}'s live claim on ${v.issues.map((n) => '#' + n).join(' ')}`;
13424
+ }
13425
+
13426
+ /** The clause the 🚢 comment carries for a hand-off land — the executor still holds its claim. */
13427
+ function handoffEvidence(v) {
13428
+ return v ? ` · landed from the executor's hand-off ${v.url} — its claim and worktree stay until it confirms the land` : '';
13429
+ }
13430
+
12912
13431
  function shipRefFor(repoAbs, branch) {
12913
13432
  const r = git.branchRefs(repoAbs, branch);
12914
13433
  return r.localSha || r.remoteSha || branch;
@@ -12916,14 +13435,14 @@ function shipRefFor(repoAbs, branch) {
12916
13435
 
12917
13436
  function cmdShip(argv) {
12918
13437
  const opts = parseArgs(argv, {
12919
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch', '--answered-by': 'answeredBy' },
13438
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch', '--answered-by': 'answeredBy', '--handoff': 'handoff' },
12920
13439
  // #479: a repeated --refs used to keep only its LAST value, and every dropped issue then became a
12921
13440
  // `Closes` line on trunk — an issue meant to stay open, auto-closed by the push. --refs now
12922
13441
  // accumulates (a repeat is the same as one comma list); every OTHER value flag to ship refuses a
12923
13442
  // repeat (`once`), checked here before any git or GitHub call.
12924
13443
  lists: { '--refs': 'refs' },
12925
13444
  once: true,
12926
- flags: { '--keep-worktree': 'keepWorktree', '--delete-branch': 'deleteBranch', '--keep-branch': 'keepBranch', '--dry': 'dry', '--json': 'json', '--direct': 'direct', '--adopt': 'adopt', '-h': 'help', '--help': 'help' },
13445
+ flags: { '--keep-worktree': 'keepWorktree', '--delete-branch': 'deleteBranch', '--keep-branch': 'keepBranch', '--dry': 'dry', '--json': 'json', '--direct': 'direct', '--adopt': 'adopt', '--split': 'split', '-h': 'help', '--help': 'help' },
12927
13446
  });
12928
13447
  if (opts.help) return print(HELP_SHIP);
12929
13448
  // --json is scoped to --dry only (#77): a machine-readable READ of the preconditions. Reporting
@@ -12931,6 +13450,11 @@ function cmdShip(argv) {
12931
13450
  // — refuse the combination rather than silently ignore --json on a real ship.
12932
13451
  if (opts.json && !opts.dry) throw new UserError('--json currently only applies together with --dry — see `colab ship --help`');
12933
13452
  if (shippedBranch.conflictingFlags(opts)) throw new UserError('--delete-branch and --keep-branch contradict each other — pass one (see `colab ship --help`, #368)');
13453
+ // #578: a hand-off names ONE branch; trunk-direct has no branch for it to name. #591: in a batch the
13454
+ // hand-off rides its member (`--batch b1,b2@<url>`), so a bare --handoff beside --batch names no one.
13455
+ 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`)');
13456
+ if (opts.handoff && opts.direct) throw new UserError('--handoff applies to one --branch ship — not to --direct (see `colab ship --help`)');
13457
+ 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');
12934
13458
  if (opts.batch) return cmdShipBatch(opts); // #373 — its own re-entrant path; nothing below changes
12935
13459
  // A fully separate code path, deliberately: the prose/table path below is unchanged by this
12936
13460
  // feature (CONVENTIONS/#77 requires it stay byte-identical), so --dry --json does its own
@@ -12948,6 +13472,17 @@ function cmdShip(argv) {
12948
13472
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
12949
13473
  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)`);
12950
13474
 
13475
+ // #578: a remote-built branch's issue set, from its executor's recorded hand-off. Before the
13476
+ // branch-resolves check below: reading the hand-off fetches the branch, which is what makes a
13477
+ // remote-only branch resolve here at all.
13478
+ const handoff = applyShipHandoff(repoAbs, sess, opts, trunk);
13479
+ if (handoff && !handoff.ok) {
13480
+ process.stderr.write(`✗ Refusing --handoff: ${handoff.detail}. Re-run with --handoff <a hand-off naming ${sess.branch} and its current head>, ` +
13481
+ `ship from the executor's machine, or a human takes the claim over (\`colab claim <N> --branch ${sess.branch} --force\`, a human act).\n`);
13482
+ process.stderr.write(' Nothing was claimed or taken over here — the executor\'s claim still stands.\n');
13483
+ return 1;
13484
+ }
13485
+
12951
13486
  // ---- the recorded branch must RESOLVE, before anything else is computed ----
12952
13487
  // Everything downstream is keyed to this name: the claim lookup above, the migration diff, the
12953
13488
  // squash. A worktree record holding a role word or a deleted branch fails all three quietly —
@@ -13007,6 +13542,7 @@ function cmdShip(argv) {
13007
13542
  const gh = isGhUsable(repoAbs);
13008
13543
  // #345: the gate that passed is the table's first row, so a reader sees WHICH door opened it.
13009
13544
  const checks = [['✓', 'autonomy granted', autonomyGate.detail]];
13545
+ if (handoff) checks.push(['✓', 'hand-off verified (#578)', handoffDetail(handoff)]);
13010
13546
 
13011
13547
  // Which claimed issues are REFERENCED (Refs #N), not closed — three sources unioned by
13012
13548
  // resolveCloseRefsSplit (#48, #74): --refs, the tracking label, and #74's close gate (an
@@ -13118,6 +13654,11 @@ function cmdShip(argv) {
13118
13654
  const coreReview = shipCoreReview(repoAbs, gh, target, sess.branch);
13119
13655
  const coreOk = coreReview.verdict !== 'refuse';
13120
13656
  checks.push([coreOk ? (coreReview.verdict === 'pending' ? '⏸' : '✓') : '✗', 'core-path review (#350)', coreReview.detail]);
13657
+
13658
+ // #581: a batch in flight at trunk's tip holds the lane. Like the core-path review's 'pending', a
13659
+ // hold is not a failed precondition — it is a pause, taken below once every real one has passed.
13660
+ const lane = shipBatchLaneCheck(repoAbs, doc, trunk, target, gh);
13661
+ if (lane) checks.push([lane.held ? '⏸' : '✓', 'no batch in flight (#581)', lane.detail]);
13121
13662
  for (const w of coreReview.warnings) warn(`${coreReview.codeownersPath}: ${w}`);
13122
13663
 
13123
13664
  // #389: the record this ship will write after the push must be writable NOW.
@@ -13352,6 +13893,8 @@ function cmdShip(argv) {
13352
13893
  print(' Plan: no merge, no commit, no push · post evidence comment + CLOSE each issue · ' +
13353
13894
  (opts.keepWorktree ? 'keep worktree' : 'worktree rm') + ' (releases claims)');
13354
13895
  print(' Gate: every closing issue must already carry an evidence comment — checked at run time.');
13896
+ } else if (lane && lane.held && coreReview.verdict !== 'pending') {
13897
+ print(` Plan: PAUSE (⏸ exit 3, nothing merged) — ${lane.ref} holds the ${trunk} lane (#581); run again once it has landed or been declined`);
13355
13898
  } else if (coreReview.verdict === 'pending') {
13356
13899
  print(` Plan: push ${sess.branch} · ${coreReview.pr ? `PR #${coreReview.pr.number} already open` : 'open a PR → ' + target} · ` +
13357
13900
  'PAUSE (⏸ exit 3, no squash) until an account other than the author approves the current head (#350)');
@@ -13417,6 +13960,9 @@ function cmdShip(argv) {
13417
13960
  return shipOpenCorePr(repoAbs, coreReview, { target, branch: sess.branch, title, body });
13418
13961
  }
13419
13962
 
13963
+ // ---- (b5) #581: a batch holds the trunk lane — pause before B0, so nothing is synced or merged ----
13964
+ if (lane && lane.held) { printBatchLanePause(lane, trunk); return 3; }
13965
+
13420
13966
  // ---- (c) B0: merge the TARGET into the branch (in the worktree, or an ephemeral one) ----
13421
13967
  const generated = [...DEFAULT_GENERATED, ...(Array.isArray(doc.generated) ? doc.generated.map(String) : [])];
13422
13968
  const hasPreShip = fs.existsSync(path.join(repoAbs, '.colab', 'hooks', 'pre-ship'));
@@ -13562,6 +14108,10 @@ function cmdShip(argv) {
13562
14108
  ciGrantForTrailer = ciResultB1.grantVerdict;
13563
14109
  }
13564
14110
  }
14111
+ // #581: re-read the lane right before the merge — B0 sits between the table and here, and a batch
14112
+ // built in that window is exactly as live as one the table saw.
14113
+ const laneB1 = lane ? shipBatchLaneCheck(repoAbs, doc, trunk, target, gh) : null;
14114
+ if (laneB1 && laneB1.held) { cleanupEphemeral(); printBatchLanePause(laneB1, trunk); return 3; }
13565
14115
  // WHERE the squash happens. Into trunk it is the main checkout, which is on trunk by invariant
13566
14116
  // (and was just verified to be). Into a declared line it must NOT be: checking the main checkout
13567
14117
  // out onto a long-lived line is the very state that made this axis necessary — everything reading
@@ -13679,7 +14229,7 @@ function cmdShip(argv) {
13679
14229
  (publicOmit ? (m) => print(` ${m}`) : warn)(`Machine trailer ${machineTrailerSummary(trailerDecision)}`);
13680
14230
  }
13681
14231
  const machineLine = trailerDecision.line;
13682
- const ciTrailerLines = [ciTrailer, adoptTrailer, machineLine].filter(Boolean);
14232
+ const ciTrailerLines = [ciTrailer, adoptTrailer, shipHandoff.handoffTrailer(sess.handoff), machineLine].filter(Boolean);
13683
14233
  if (opts.message) {
13684
14234
  // --message overrides the subject/body, but Closes is spliced in as its own paragraph — never
13685
14235
  // concatenated. Appending it welded ` — Closes #N` onto whatever the message ended with, which
@@ -13688,7 +14238,7 @@ function cmdShip(argv) {
13688
14238
  for (const tl of ciTrailerLines) {
13689
14239
  if (commitMsg.toLowerCase().includes(tl.toLowerCase())) continue;
13690
14240
  const lastLine = commitMsg.split('\n').pop().trim();
13691
- 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;
14241
+ 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;
13692
14242
  }
13693
14243
  } else {
13694
14244
  // Preserve the branch's crafted commit (subject + footers); insert Closes/Refs above the footers.
@@ -13850,11 +14400,13 @@ function cmdShip(argv) {
13850
14400
  // a long ship these lines would otherwise scroll off above the `✓ Shipped` line — which is
13851
14401
  // exactly how #304's failure went unnoticed in the first place.
13852
14402
  deferredCollector = [];
14403
+ let reviewPrHandled = null; // #584: the #350 review PR, already closed (or warned about) above
13853
14404
  // #350: the approved PR is spent — its work landed by squash, which the forge cannot see as a merge.
13854
14405
  if (coreReview.verdict === 'approved' && coreReview.pr && gh) {
13855
14406
  const closed = git.ghPrClose(repoAbs, coreReview.pr.number, `Landed on \`${target}\` as ${sha} by \`colab ship\` (#350), approved by ${coreReview.approval.by}.`);
13856
14407
  if (closed.ok) print(` closed PR #${coreReview.pr.number} (landed as ${sha})`);
13857
14408
  else warnDeferred(`could not close PR #${coreReview.pr.number} (${(closed.stderr || '').split('\n')[0]}) — it landed as ${sha}; close it by hand`);
14409
+ reviewPrHandled = coreReview.pr.number; // #584: either way the tail's landed-PR close must not touch it again
13858
14410
  }
13859
14411
  // Only when the target IS the shared checkout. `ephemeralTarget === false` means
13860
14412
  // `targetDir === repoAbs` (see #234's note above); a declared integration line merged in a
@@ -13898,7 +14450,7 @@ function cmdShip(argv) {
13898
14450
  pushEvent('ship', {
13899
14451
  repo: repoAbs, worktree: sess.name, session: sess.session,
13900
14452
  issue: sess.issues.length === 1 ? sess.issues[0] : undefined,
13901
- payload: { state: 'merged', branch: sess.branch, target, sha, issues: sess.issues, ...(adoptInfo ? { adopted: adoptInfo } : {}) },
14453
+ 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 } } : {}) },
13902
14454
  });
13903
14455
 
13904
14456
  // Then, PER ISSUE, a merge-completion event (#46 §2, following #45 §2). The ship event above is
@@ -13920,11 +14472,13 @@ function cmdShip(argv) {
13920
14472
  // window itself now OPENS at the push (e2, #304), not here: post-ship's warnings belong in the
13921
14473
  // same block, and re-assigning the collector here would silently discard them.
13922
14474
  shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts,
13923
- evidenceExtra: opts.humanDoorEvidence || '' }); // #525
14475
+ skipPrs: reviewPrHandled ? [reviewPrHandled] : [],
14476
+ evidenceExtra: (opts.humanDoorEvidence || '') + handoffEvidence(sess.handoff) }); // #525, #578
13924
14477
 
13925
14478
  print('');
13926
14479
  print(`✓ Shipped ${sess.branch} → ${target} @ ${sha}${sess.issues.length ? ' (' + sess.issues.map((n) => '#' + n).join(' ') + ')' : ''}`);
13927
14480
  if (adoptInfo) print(` adopted from ${adoptInfo.remote || 'origin'}/${adoptInfo.branch} @ ${shortSha(adoptInfo.remoteSha)} — recorded in the Colab-Adopted: trailer (#324)`);
14481
+ 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)`);
13928
14482
  if (target !== trunk) print(` "${target}" is a declared line: this work is NOT in ${trunk} until a human merges the line.`);
13929
14483
  // #114: everything deferred since the push (e2, #304) lands here, AFTER the success line — not scattered above it
13930
14484
  // where a long ship scrolls it out of view. The merge itself already landed either way; this is
@@ -13938,6 +14492,38 @@ function cmdShip(argv) {
13938
14492
  }
13939
14493
 
13940
14494
 
14495
+ /**
14496
+ * #584: close every open PR whose head is the branch this ship just landed — the PR a person or an
14497
+ * automation opened only to obtain branch CI. The forge never sees a squash as a merge of that PR, so
14498
+ * without this it stays open forever, reading as unmerged work. Only a PR whose head commit is the
14499
+ * landed tip (or an ancestor of it) is closed; one carrying commits that did not land is kept and
14500
+ * reported. Best-effort throughout: every failure defers a warning, none fails the ship.
14501
+ */
14502
+ function shipCloseLandedPrs(repoAbs, sess, { target, sha, issues, skip = [] }) {
14503
+ const remoteName = git.remoteInfo(repoAbs).name || 'origin';
14504
+ const tipOf = (ref) => { const r = git.git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], repoAbs); return r.ok ? r.stdout.trim() : null; };
14505
+ const tip = tipOf(`refs/heads/${sess.branch}`) || tipOf(`refs/remotes/${remoteName}/${sess.branch}`);
14506
+ const headLanded = (oid) => {
14507
+ if (!tip) return false;
14508
+ if (oid === tip) return true;
14509
+ return git.git(['merge-base', '--is-ancestor', oid, tip], repoAbs).ok;
14510
+ };
14511
+ const res = landedPrs.closeLandedPrs({
14512
+ prs: git.ghOpenPrsForBranch(repoAbs, sess.branch),
14513
+ headLanded,
14514
+ close: (n, comment) => git.ghPrClose(repoAbs, n, comment),
14515
+ comment: landedPrs.landedPrComment({ target, sha, issues }),
14516
+ skip,
14517
+ });
14518
+ if (res.listError) {
14519
+ warnDeferred(`could not list open PRs for ${sess.branch} (${res.listError}) — any PR opened for its CI is still open; close it by hand (it landed as ${sha})`);
14520
+ return;
14521
+ }
14522
+ for (const n of res.closed) print(` closed PR #${n} — its branch ${sess.branch} landed as ${sha} (#584)`);
14523
+ for (const f of res.failed) warnDeferred(`could not close PR #${f.number} (${f.error}) — ${sess.branch} landed as ${sha}; close it by hand`);
14524
+ for (const k of res.kept) warnDeferred(`kept PR #${k.number} open: ${k.reason} (${sess.branch} landed as ${sha}) — it carries work that did not ship`);
14525
+ }
14526
+
13941
14527
  /**
13942
14528
  * The post-merge tail every landed branch gets — cmdShip's B3 through i2, moved here unchanged (#373)
13943
14529
  * so a batch member gets exactly the same steps in the same order: worktree teardown (B3), the claims
@@ -13946,7 +14532,13 @@ function cmdShip(argv) {
13946
14532
  * addition — '' on a serial ship (so its comment is byte-identical), the combined-run clause for a
13947
14533
  * batch member.
13948
14534
  */
13949
- function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts, evidenceExtra = '' }) {
14535
+ function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts, evidenceExtra = '', skipPrs = [] }) {
14536
+ // #584: the CI-trigger PR(s) this squash left behind. FIRST, while the branch ref still resolves —
14537
+ // B3 below may delete it, and "did the PR's head land?" is answered against that tip.
14538
+ if (gh && sess.branch) {
14539
+ try { shipCloseLandedPrs(repoAbs, sess, { target, sha, issues: closeIssues, skip: skipPrs }); }
14540
+ catch (e) { warnDeferred(`landed-PR close for ${sess.branch} failed (${e.message}) — the ship landed as ${sha}; close any PR for it by hand`); }
14541
+ }
13950
14542
  const worktreeKept = !!(sess.name && opts.keepWorktree);
13951
14543
  if (sess.name && !opts.keepWorktree) {
13952
14544
  print(`B3: removing worktree ${sess.name} …`);
@@ -13966,7 +14558,8 @@ function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, re
13966
14558
  // B3 (cont.) — the shipped branch. Kept by default; --delete-branch opts in. MUST come after the
13967
14559
  // worktree removal above: git refuses to delete a branch checked out in a worktree.
13968
14560
  // #368: a Refs-only ship deletes unless --keep-branch — see tools/lib/shipped-branch.js.
13969
- const disposition = shippedBranch.shippedBranchDisposition({ closeIssues, refsIssues, deleteBranch: opts.deleteBranch, keepBranch: opts.keepBranch });
14561
+ // #578: a handed-off branch is the executor's until it confirms the land — never deleted for it.
14562
+ const disposition = shippedBranch.shippedBranchDisposition({ closeIssues, refsIssues, deleteBranch: opts.deleteBranch, keepBranch: opts.keepBranch || (!!sess.handoff && !opts.deleteBranch) });
13970
14563
  handleShippedBranch(repoAbs, target, sess.branch, { disposition, worktreeKept, integration });
13971
14564
 
13972
14565
  // ---- (g/h) B4 verify + post summary per issue ----
@@ -14082,6 +14675,46 @@ function shipDryJsonReport(opts) {
14082
14675
  return { ok: code === 0, body: holder.body || null, error: null };
14083
14676
  }
14084
14677
 
14678
+ /**
14679
+ * #581: is a batch in flight at trunk's current tip? Read by every serial door that moves trunk (the
14680
+ * prose ship's table and B1, `--dry --json`), so a lander told about it waits instead of moving trunk
14681
+ * under the batch — which would throw the batch's green combined run away. The rule is
14682
+ * lib/ship-batch.js laneHold; this only reads the remote.
14683
+ *
14684
+ * Inert (null, no git or gh call) unless project.yml declares ship-batch > 1, the merge target is
14685
+ * trunk, and gh is usable. Out: null, or `{ held, ref, why, released, detail }`.
14686
+ */
14687
+ function shipBatchLaneCheck(repoAbs, doc, trunk, target, gh) {
14688
+ if (target !== trunk || !gh || shipBatch.parseShipBatch(doc).n <= 1) return null;
14689
+ const remote = git.remoteFor(repoAbs);
14690
+ const ls = git.git(['ls-remote', remote, `refs/heads/${trunk}`, 'refs/heads/ship-batch/*'], repoAbs);
14691
+ if (!ls.ok) return { held: false, released: [], detail: `could not read ${remote} — no batch provably in flight` };
14692
+ const rows = ls.stdout.split('\n').map((l) => l.split('\t')).filter(([sha, ref]) => sha && ref);
14693
+ const trunkNow = ((rows.find(([, ref]) => ref.trim() === `refs/heads/${trunk}`) || [])[0] || '').trim();
14694
+ const atTip = rows.map(([sha, ref]) => ({ sha: sha.trim(), parsed: shipBatch.parseBatchRef(ref.trim()) }))
14695
+ .filter((x) => x.parsed && trunkNow.startsWith(x.parsed.base7));
14696
+ const batches = atTip.map((x) => {
14697
+ const runs = git.ghRunsForRef(repoAbs, x.parsed.ref, x.sha);
14698
+ let t = git.git(['log', '-1', '--format=%cI', x.sha], repoAbs);
14699
+ if (!t.ok) { git.git(['fetch', '-q', remote, `refs/heads/${x.parsed.ref}`], repoAbs); t = git.git(['log', '-1', '--format=%cI', x.sha], repoAbs); }
14700
+ const built = t.ok ? Date.parse(t.stdout.trim()) : NaN;
14701
+ return { ref: x.parsed.ref, base7: x.parsed.base7, verdict: shipBatch.combinedVerdict(runs),
14702
+ builtAtMs: Number.isFinite(built) ? built : null, settledAtMs: shipBatch.settledAt(runs) };
14703
+ });
14704
+ const r = shipBatch.laneHold({ batches, trunkNow, nowMs: Date.now() });
14705
+ const detail = r.held
14706
+ ? `${r.ref} holds the ${trunk} lane — ${r.why}; landing now would move ${trunk} under it and discard its run`
14707
+ : (r.released.length ? `no batch holds the lane (${r.released.map((x) => `${x.ref}: ${x.why}`).join('; ')})` : `no batch in flight at ${trunk}@${shortSha(trunkNow)}`);
14708
+ return { ...r, trunkNow, detail };
14709
+ }
14710
+
14711
+ /** #581: the pause a serial ship takes while a batch holds the trunk lane — one message, every door. */
14712
+ function printBatchLanePause(lane, trunk) {
14713
+ print(`⏸ BATCH-IN-FLIGHT ${lane.ref} — ${lane.why}. Nothing landed.`);
14714
+ print(` Landing now would move ${trunk} under it and throw its combined run away (#581). Wait for it to land`);
14715
+ print(' or be declined (bounded, B1a — the same wait as any CI run), then run this command again.');
14716
+ }
14717
+
14085
14718
  function cmdShipBatch(opts) {
14086
14719
  for (const [key, flag] of [['direct', '--direct'], ['worktree', '--worktree'], ['branch', '--branch'], ['message', '--message'], ['refs', '--refs'], ['adopt', '--adopt'], ['json', '--json']]) {
14087
14720
  if (opts[key]) throw new UserError(`--batch does not combine with ${flag} — each member ships with its own recorded claims and composed message (#373)`);
@@ -14091,7 +14724,11 @@ function cmdShipBatch(opts) {
14091
14724
  const doc = projectDoc(repoAbs);
14092
14725
  const trunk = resolveTrunk(repoAbs, doc);
14093
14726
  if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
14094
- const members = [...new Set(String(opts.batch === true ? '' : opts.batch).split(',').map((s) => s.trim()).filter(Boolean))];
14727
+ // #591: a member built on another machine names its hand-off inline — `<branch>@<hand-off-url>`.
14728
+ const entries = shipHandoff.parseBatchEntries(opts.batch === true ? '' : opts.batch);
14729
+ if (entries.errors.length) throw new UserError(`--batch: ${entries.errors.join('; ')}`);
14730
+ const members = entries.members;
14731
+ const handoffs = entries.handoffs;
14095
14732
  if (members.includes(trunk)) throw new UserError(`Refusing: ${trunk} is the trunk itself — it cannot be a batch member`);
14096
14733
  const serial = (why, list = members) => {
14097
14734
  print(`✗ ship-batch: ${why}`);
@@ -14104,17 +14741,32 @@ function cmdShipBatch(opts) {
14104
14741
  if (String(doc.autonomy || '') !== 'auto-trunk') {
14105
14742
  return serial(`project.yml does not grant autonomy: auto-trunk — batch landing needs it (every member lands in one unattended push)`);
14106
14743
  }
14107
- // #555: a declared ship-batch-wait lets ONE named member through — it may wait for a partner below.
14744
+ // #555: a declared ship-batch-wait makes a lone member wait for a partner below.
14745
+ // #562: one named member is a valid batch — it lands through the combined run, never serially.
14108
14746
  const waitCfg = shipBatch.parseShipBatchWait(doc);
14109
14747
  if (!waitCfg.valid) warn(`${waitCfg.reason} — ignored: a lone member does not wait (fails closed, #555)`);
14110
- if (members.length < 2 && !(members.length === 1 && waitCfg.sec > 0)) return serial(`--batch names ${members.length} branch(es) — a batch needs at least two`);
14111
- if (members.length > cfg.n) warn(`--batch names ${members.length} branches; ship-batch: ${cfg.n} caps the batch — the rest wait for the next one`);
14748
+ if (members.length < 1) return serial('--batch names no branch — name every ready candidate');
14112
14749
 
14113
14750
  const remote = git.remoteFor(repoAbs);
14114
14751
  const fetched = git.git(['fetch', '--prune', remote], repoAbs);
14115
14752
  if (!fetched.ok) throw new UserError(`could not fetch ${remote}: ${git.gitFailureLine(fetched.stderr)} — a batch is never built from stale refs`);
14116
14753
  const trunkRef = `${remote}/${trunk}`;
14117
14754
 
14755
+ // #557: the size this batch is built at — fixed at ship-batch without steps; with them, one step
14756
+ // above the last landed batch's size after a green, one below after a red, read from trunk alone.
14757
+ const stepsCfg = shipBatch.parseShipBatchSteps(doc);
14758
+ if (!stepsCfg.valid) warn(`${stepsCfg.reason} — ignored: every batch is up to ship-batch: ${cfg.n} (fails closed, #557)`);
14759
+ let lastSize = null;
14760
+ if (stepsCfg.steps) {
14761
+ const lg = git.git(['log', '-1', '--first-parent', `--grep=^${shipBatch.SIZE_TRAILER_KEY}: `, '--format=%B', trunkRef], repoAbs);
14762
+ lastSize = lg.ok ? shipBatch.parseSizeTrailer([lg.stdout]) : null;
14763
+ }
14764
+ const size = shipBatch.adaptiveSize({ n: cfg.n, steps: stepsCfg.steps, last: lastSize });
14765
+ const sizeLabel = stepsCfg.steps
14766
+ ? `ship-batch: ${cfg.n} · step ${size} of ${stepsCfg.steps.join(',')}${lastSize ? ` — the last landed batch was ${lastSize.red ? `a split of a red one at ${lastSize.size}` : `green at ${lastSize.size}`}` : ' — no sized batch on trunk yet'}`
14767
+ : `ship-batch: ${cfg.n}`;
14768
+ if (members.length > size) warn(`--batch names ${members.length} branches; ${sizeLabel} caps the batch — the rest wait for the next one`);
14769
+
14118
14770
  // ---- (a) wiring: could the combined run ever arrive? Decided BEFORE anything is pushed. ----
14119
14771
  const fires = workflowsFiringAt(repoAbs, trunkRef, shipBatch.PROBE_REF);
14120
14772
  if (!shipBatch.wiring(fires).wired) {
@@ -14173,8 +14825,9 @@ function cmdShipBatch(opts) {
14173
14825
  }
14174
14826
  if (!foreignStep) {
14175
14827
  const heads = inBatch.map((m) => ({ ...m, now: git.branchRefs(repoAbs, m.branch, remote).remoteSha }));
14176
- const matches = heads.length >= 2 && heads.every((m) => m.now && m.now.startsWith(m.sha));
14177
- existing = { ref: atBase.parsed.ref, base7: atBase.parsed.base7, sha: atBase.sha, members: inBatch, matches };
14828
+ const matches = heads.length >= 1 && heads.every((m) => m.now && m.now.startsWith(m.sha));
14829
+ existing = { ref: atBase.parsed.ref, base7: atBase.parsed.base7, sha: atBase.sha, members: inBatch, matches,
14830
+ size: shipBatch.parseSizeTrailer(log.ok ? log.stdout.split('\0') : []) };
14178
14831
  // #415: the command line and the staged batch can name different sets. A requested branch the
14179
14832
  // staged batch does not carry (over the cap, dropped at build, or added since) does NOT ride
14180
14833
  // along — say so, naming both lists, instead of resuming as if the two were the same.
@@ -14186,7 +14839,10 @@ function cmdShipBatch(opts) {
14186
14839
  }
14187
14840
  }
14188
14841
  const verdict = existing && existing.matches ? shipBatch.combinedVerdict(git.ghRunsForRef(repoAbs, existing.ref, existing.sha)) : null;
14189
- let step = shipBatch.nextStep({ enabled: true, wired: true, trunkCi, eligibleCount: 2, existing, trunkNow, verdict });
14842
+ let step = shipBatch.nextStep({ enabled: true, wired: true, trunkCi, eligibleCount: members.length, existing, trunkNow, verdict, split: !!opts.split });
14843
+ if (opts.split && !(verdict && verdict.state === 'red')) {
14844
+ print(` --split ignored: ${existing ? `${existing.ref} is not red (${verdict ? verdict.state : 'members changed'})` : 'no batch is staged at this base'} — only a red combined run splits (#557)`);
14845
+ }
14190
14846
 
14191
14847
  if (step.step === 'rebuild') {
14192
14848
  print(` ${existing.ref} no longer carries the requested members at their current heads — rebuilding`);
@@ -14208,6 +14864,24 @@ function cmdShipBatch(opts) {
14208
14864
  print(shipBatch.serialLine(existing.members.map((m) => m.branch)));
14209
14865
  return 4;
14210
14866
  }
14867
+ if (step.step === 'red-rerun-or-split') {
14868
+ const ids = verdict.runIds.join(', ') || '(id unread)';
14869
+ const cmd = `colab ship --batch ${members.join(',')} --split${opts.repo ? ` --repo ${opts.repo}` : ''}`;
14870
+ print(`✗ ship-batch: the combined run is red at ${existing.ref}@${shortSha(existing.sha)} (${verdict.why}; run ${ids}). Nothing landed.`);
14871
+ print(` ${existing.members.length} members — it splits rather than going serial (#557). Classify it first (CONVENTIONS §4, Branch CI):`);
14872
+ for (const id of verdict.runIds) print(` red:infra → gh run rerun ${id} --failed then run this command again (one re-run only)`);
14873
+ print(` red:finding → ${cmd}`);
14874
+ print(' rebuilds this batch with its first half; the rest wait for the next batch');
14875
+ return 4;
14876
+ }
14877
+ let splitHalf = null;
14878
+ if (step.step === 'split') {
14879
+ const { first, held } = shipBatch.splitHalves(existing.members);
14880
+ splitHalf = { first, held, parentSize: existing.size ? existing.size.size : existing.members.length };
14881
+ print(`✗ ship-batch: the combined run is red at ${existing.ref}@${shortSha(existing.sha)} (${verdict.why}${verdict.attempt >= 2 ? ', after its one re-run' : ''}). Nothing landed.`);
14882
+ print(` splitting (#557): testing ${first.map((m) => m.branch).join(', ')} on the same base; held for the next batch: ${held.map((m) => m.branch).join(', ')}`);
14883
+ step = { step: 'build' };
14884
+ }
14211
14885
  if (step.step === 'red-serial') {
14212
14886
  print(`✗ ship-batch: the combined run is red again after its one re-run (${verdict.why}) — nothing landed; ${existing.ref} ${opts.dry ? 'would be deleted [DRY RUN]' : 'deleted'}.`);
14213
14887
  deleteRef(existing.ref);
@@ -14225,13 +14899,19 @@ function cmdShipBatch(opts) {
14225
14899
  if (!refs.remoteSha) why = `not on ${remote} — push it first; its CI has never seen it`;
14226
14900
  else if (refs.localSha && refs.localSha !== refs.remoteSha) why = `local ${shortSha(refs.localSha)} ≠ ${remote} ${shortSha(refs.remoteSha)} — its CI never saw this head`;
14227
14901
  if (!why) {
14228
- const rep = shipDryJsonReport({ repo: repoAbs, branch: b, dry: true, json: true, session: opts.session, sessionName: opts.sessionName });
14902
+ // #591: a hand-off member is read through the SAME door a single --handoff ship uses
14903
+ // (applyShipHandoff inside cmdShipDryJson) — one verification, never a batch-local copy.
14904
+ const rep = shipDryJsonReport({ repo: repoAbs, branch: b, dry: true, json: true, session: opts.session, sessionName: opts.sessionName,
14905
+ ...(handoffs[b] ? { handoff: handoffs[b] } : {}) });
14229
14906
  report = rep.body;
14230
14907
  files = branchChangedFiles(repoAbs, trunkRef, refs.remoteSha);
14231
14908
  ciClass = shipBatch.branchCiClass(git.ghRunForSha(repoAbs, b), workflowsFiringAt(repoAbs, refs.remoteSha, b).length > 0);
14232
- const el = rep.error ? { ok: false, why: rep.error } : shipBatch.memberEligibility(report, ciClass, {
14233
- trunk, touchesWorkflows: files.some((f) => f.startsWith('.github/workflows/')),
14234
- });
14909
+ const el = rep.error ? { ok: false, why: rep.error }
14910
+ // #591: a refused hand-off is worded as the single door words it — the same reason, the same detail.
14911
+ : (report && report.handoff && !report.handoff.ok) ? { ok: false, why: `Refusing --handoff: ${report.handoff.detail}` }
14912
+ : shipBatch.memberEligibility(report, ciClass, {
14913
+ trunk, touchesWorkflows: files.some((f) => f.startsWith('.github/workflows/')),
14914
+ });
14235
14915
  if (!el.ok) why = el.why;
14236
14916
  }
14237
14917
  evaluated.push({ branch: b, sha: refs.remoteSha, report, ciClass, files, ok: !why, why: why || `own head CI: ${ciClass}` });
@@ -14240,13 +14920,21 @@ function cmdShipBatch(opts) {
14240
14920
  // #387: a generated path shared by two members is not an overlap — the build regenerates it (below).
14241
14921
  const generated = [...DEFAULT_GENERATED, ...(Array.isArray(doc.generated) ? doc.generated.map(String) : [])];
14242
14922
  const hasPreShip = fs.existsSync(path.join(repoAbs, '.colab', 'hooks', 'pre-ship'));
14243
- const { selected, overflow } = shipBatch.selectMembers(eligible, cfg.n, { isGenerated: (f) => isGeneratedPath(f, generated) });
14244
- print(`ship --batch ${shortRepo(repoAbs)} → ${trunk} @ ${shortSha(trunkNow)} (ship-batch: ${cfg.n})${opts.dry ? ' [DRY RUN]' : ''}`);
14923
+ // #557: a split builds exactly its first half, in the red batch's order — the pre-sort is not re-run,
14924
+ // or a different subset would be tested and the bisection would not narrow.
14925
+ const { selected, overflow } = splitHalf
14926
+ ? (() => {
14927
+ const want = splitHalf.first.map((m) => m.branch);
14928
+ const sel = want.map((b) => eligible.find((e) => e.branch === b)).filter(Boolean);
14929
+ return { selected: sel, overflow: eligible.filter((e) => !sel.includes(e)) };
14930
+ })()
14931
+ : shipBatch.selectMembers(eligible, size, { isGenerated: (f) => isGeneratedPath(f, generated) });
14932
+ print(`ship --batch ${shortRepo(repoAbs)} → ${trunk} @ ${shortSha(trunkNow)} (${splitHalf ? `split of a red batch of ${splitHalf.first.length + splitHalf.held.length}` : sizeLabel})${opts.dry ? ' [DRY RUN]' : ''}`);
14245
14933
  print(table(evaluated.map((e) => [e.ok ? (selected.includes(e) ? '✓' : '·') : '✗', e.branch,
14246
- e.ok && !selected.includes(e) ? `eligible — waits for the next batch (cap ${cfg.n})` : e.why]), ['', 'MEMBER', 'DETAIL']));
14934
+ e.ok && !selected.includes(e) ? (splitHalf ? 'eligible — held by the split for the next batch' : `eligible — waits for the next batch (cap ${size})`) : e.why]), ['', 'MEMBER', 'DETAIL']));
14247
14935
  const notJoining = evaluated.filter((e) => !selected.includes(e)).map((e) => e.branch);
14248
14936
  step = shipBatch.nextStep({ enabled: true, wired: true, trunkCi, eligibleCount: selected.length, existing: null, trunkNow });
14249
- if (step.step === 'serial' && selected.length === 1 && waitCfg.sec > 0) {
14937
+ if (step.step === 'build' && selected.length === 1 && waitCfg.sec > 0 && !splitHalf) {
14250
14938
  // #555: the lane is idle here (trunk's run finished, no batch in flight at this base), and one
14251
14939
  // member is ready. Wait for a partner until the repo's window, counted from when it became ready.
14252
14940
  const lone = selected[0];
@@ -14256,13 +14944,13 @@ function cmdShipBatch(opts) {
14256
14944
  if (pw.wait) {
14257
14945
  print(`⏸ PARTNER-WAIT ${lone.branch} — the only ready member; ${waitCfg.reason}, ready since ${new Date(since).toISOString()}, ${ciWait.fmtDuration(pw.leftSec * 1000)} left. Nothing landed.`);
14258
14946
  print(` Wait up to ${pw.leftSec}s (a wait on another candidate's run counts toward it), gather EVERY ready candidate again,`);
14259
- print(' then run colab ship --batch with all of them. Past the window, this same call lands it alone (serial).');
14947
+ print(' then run colab ship --batch with all of them. Past the window, this same call lands it alone, as a batch of one.');
14260
14948
  return 3;
14261
14949
  }
14262
14950
  const why = { 'window-elapsed': `${waitCfg.reason} has elapsed since it became ready`, 'ready-time-unread': 'its ready time could not be read, so it does not wait' }[pw.reason] || pw.reason;
14263
- return serial(`1 member can join and no partner arrived — ${why}`);
14951
+ print(` no partner arrived for ${lone.branch} — ${why}; building a batch of one (the combined run still gates it, #562)`);
14264
14952
  }
14265
- if (step.step === 'serial') return serial(`${selected.length} member(s) can join — a batch needs at least two`);
14953
+ if (step.step === 'serial') return serial('no member can join — each one above says why');
14266
14954
 
14267
14955
  // ---- (e) build: trunk head + one squash commit per member, in an ephemeral detached worktree ----
14268
14956
  const ref = shipBatch.batchRefName(trunkNow);
@@ -14321,8 +15009,9 @@ function cmdShipBatch(opts) {
14321
15009
  const closeIssues = m.report.closeIssues || [];
14322
15010
  const refsIssues = m.report.refsIssues || [];
14323
15011
  const conflicts = [];
15012
+ // #591: a hand-off member's squash records the door its issue set came through, as a single ship's does.
14324
15013
  const msg = buildSquashMessage(repoAbs, trunkRef, m.sha, closeIssues, refsIssues, conflicts,
14325
- [machineLine, shipBatch.memberTrailer({ ref, branch: m.branch, sha: m.sha })].filter(Boolean));
15014
+ [shipHandoff.handoffTrailer(m.report.handoff), machineLine, shipBatch.memberTrailer({ ref, branch: m.branch, sha: m.sha })].filter(Boolean));
14326
15015
  const coverage = msg ? shipguard.closesCoverage({ message: msg, closeIssues, refsIssues, commits: branchCommits(repoAbs, trunkRef, m.sha) }) : { ok: false, missing: [] };
14327
15016
  const inherited = msg && refsIssues.length ? squash.inheritedClosingKeywordConflicts(msg, refsIssues) : [];
14328
15017
  if (!msg || !coverage.ok || inherited.length) {
@@ -14337,22 +15026,26 @@ function cmdShipBatch(opts) {
14337
15026
  for (const d of dropped) print(` ✗ ${d.branch}: ${d.why}`);
14338
15027
  // #554: a drop leaves a durable trace — one Ship-Batch-Dropped trailer per dropped member on the
14339
15028
  // batch head, so it reaches trunk with a landed batch and rides a red combined run's head message.
14340
- // Only when the batch is built (≥2 members): a build that collapses to serial pushes nothing.
14341
- if (dropped.length && built.length >= 2) {
15029
+ // Only when the batch is built (≥1 member, #562): a build that collapses to serial pushes nothing.
15030
+ // #557: with steps declared (or on a split), the head also carries the size it was built at, so the
15031
+ // next build reads the lane's last outcome from trunk alone.
15032
+ const sizeLine = splitHalf ? shipBatch.sizeTrailer({ size: splitHalf.parentSize, red: true })
15033
+ : (stepsCfg.steps ? shipBatch.sizeTrailer({ size }) : null);
15034
+ if ((dropped.length || sizeLine) && built.length >= 1) {
14342
15035
  const last = built[built.length - 1];
14343
15036
  const cur = git.git(['log', '-1', '--format=%B'], dir);
14344
- const lines = dropped.map((d) => shipBatch.droppedTrailer({ ref, branch: d.branch, sha: d.sha, cls: d.cls }));
15037
+ const lines = [...dropped.map((d) => shipBatch.droppedTrailer({ ref, branch: d.branch, sha: d.sha, cls: d.cls })), ...(sizeLine ? [sizeLine] : [])];
14345
15038
  const am = cur.ok ? git.run('git', ['commit', '-q', '--amend', '-m', shipBatch.appendTrailers(cur.stdout, lines)], { cwd: dir }) : cur;
14346
15039
  if (am.ok) last.commit = git.git(['rev-parse', 'HEAD'], dir).stdout;
14347
- else warn(`could not record the dropped member(s) on the batch head: ${git.gitFailureLine(am.stderr)} — the drop is on this terminal only`);
15040
+ else warn(`could not record the dropped member(s)/size on the batch head: ${git.gitFailureLine(am.stderr)} — they are on this terminal only`);
14348
15041
  }
14349
15042
  for (const b of built.filter((x) => x.regenerated)) {
14350
15043
  print(` ↻ ${b.branch}: combined despite a generated-file overlap — ${b.regenerated.join(', ')} regenerated by .colab/hooks/pre-ship on the combined head (the combined run is the gate)`);
14351
15044
  }
14352
15045
  const head = git.git(['rev-parse', 'HEAD'], dir).stdout;
14353
- if (built.length < 2) {
15046
+ if (built.length < 1) {
14354
15047
  cleanup();
14355
- return serial(`${built.length} member(s) survived the build — a batch needs at least two`, members);
15048
+ return serial('no member survived the build', members);
14356
15049
  }
14357
15050
  if (opts.dry) {
14358
15051
  cleanup();
@@ -14366,7 +15059,7 @@ function cmdShipBatch(opts) {
14366
15059
  cleanup();
14367
15060
  if (!push.ok) throw new UserError(`could not push ${ref}: ${git.gitFailureLine(push.stderr)} — nothing landed`);
14368
15061
  print(` pushed ${ref} = ${shortSha(trunkNow)} + ${built.length} commit(s) @ ${shortSha(head)} (${built.map((b) => b.branch).join(', ')})`);
14369
- if (overflow.length) print(` eligible but over the cap (next batch): ${overflow.map((o) => o.branch).join(', ')}`);
15062
+ if (overflow.length) print(` eligible but ${splitHalf ? 'held by the split' : 'over the cap'} (next batch): ${overflow.map((o) => o.branch).join(', ')}`);
14370
15063
  print(`⏸ BATCH-PENDING ${ref}@${shortSha(head)} — wait on the combined run (bounded, B1a), then run this command again. Nothing landed yet.`);
14371
15064
  return 3;
14372
15065
  }
@@ -14465,10 +15158,26 @@ function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opt
14465
15158
  // The post-ship hook runs ONCE, over the whole batch — it is a trunk-checkout event, not a member one.
14466
15159
  const changed = git.git(['diff', '--name-only', `${base}..${head}`], repoAbs);
14467
15160
  const hits = changed.ok ? lockfileDrift.changedLockfiles(changed.stdout.split('\n').filter(Boolean)) : [];
15161
+ // Which commit is whose — read from the trailers, never from position alone.
15162
+ const log = git.git(['log', '--format=%H%x01%B%x00', `${base}..${head}`], repoAbs);
15163
+ const commitOf = new Map();
15164
+ for (const rec of (log.ok ? log.stdout.split('\0') : [])) {
15165
+ const [sha, body] = rec.replace(/^\n+/, '').split('\x01');
15166
+ const tr = shipBatch.parseMemberTrailers([body || ''])[0];
15167
+ if (sha && tr) commitOf.set(tr.branch, { sha: sha.trim(), body: body || '' });
15168
+ }
14468
15169
  const allIssues = [];
14469
15170
  const st0 = state.loadState();
14470
15171
  const sessions = existing.members.map((m) => {
14471
15172
  const sess = resolveShipSession(st0, repoAbs, { branch: m.branch, session: opts.session, sessionName: opts.sessionName });
15173
+ // #591: a hand-off member holds no claim here. Its squash carries the Colab-Handoff trailer the
15174
+ // build verified, and the issue set is the branch name's trailing run — handoffVerdict's own rule —
15175
+ // so its tail is the single hand-off land's: Closes from git, the executor's claim and branch kept.
15176
+ const ho = sess.issues.length ? null : shipHandoff.parseHandoffTrailer((commitOf.get(m.branch) || {}).body);
15177
+ if (ho) {
15178
+ sess.issues = shipguard.branchIssueNumbers(m.branch);
15179
+ sess.handoff = { ok: true, url: ho.url, sha: m.sha, handedOff: ho.handedOff };
15180
+ }
14472
15181
  allIssues.push(...sess.issues);
14473
15182
  return sess;
14474
15183
  });
@@ -14480,14 +15189,6 @@ function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opt
14480
15189
  if (hits.length && !hook.ran) warnDeferred(lockfileDrift.driftWarning(hits));
14481
15190
  release();
14482
15191
 
14483
- // Which commit is whose — read from the trailers, never from position alone.
14484
- const log = git.git(['log', '--format=%H%x01%B%x00', `${base}..${head}`], repoAbs);
14485
- const commitOf = new Map();
14486
- for (const rec of (log.ok ? log.stdout.split('\0') : [])) {
14487
- const [sha, body] = rec.replace(/^\n+/, '').split('\x01');
14488
- const tr = shipBatch.parseMemberTrailers([body || ''])[0];
14489
- if (sha && tr) commitOf.set(tr.branch, { sha: sha.trim(), body: body || '' });
14490
- }
14491
15192
  const gh = isGhUsable(repoAbs);
14492
15193
  const suffix = shipBatch.evidenceSuffix({ n: existing.members.length, ref: existing.ref, headSha: head, runIds: verdict.runIds });
14493
15194
  existing.members.forEach((m, i) => {
@@ -14519,14 +15220,16 @@ function shipBatchMemberTail({ repoAbs, doc, trunk, sess, sha, closeIssues, refs
14519
15220
  pushEvent('ship', {
14520
15221
  repo: repoAbs, worktree: sess.name, session: sess.session,
14521
15222
  issue: sess.issues.length === 1 ? sess.issues[0] : undefined,
14522
- payload: { state: 'merged', branch: sess.branch, target: trunk, sha, issues: sess.issues, batch: true },
15223
+ payload: { state: 'merged', branch: sess.branch, target: trunk, sha, issues: sess.issues, batch: true,
15224
+ ...(sess.handoff ? { handoff: { url: sess.handoff.url, sha: sess.handoff.sha } } : {}) },
14523
15225
  });
14524
15226
  for (const num of closeIssues) pushEvent('issue-merged', { repo: repoAbs, issue: num, payload: { sha } });
14525
15227
  shipLandedTail({
14526
15228
  repoAbs, sess, target: trunk, trunk, gh, sha, closeIssues, refsIssues, refsSet: new Set(refsIssues),
14527
- integration: resolveIntegration(repoAbs, doc, trunk), opts, evidenceExtra: suffix,
15229
+ integration: resolveIntegration(repoAbs, doc, trunk), opts, evidenceExtra: suffix + handoffEvidence(sess.handoff), // #591
14528
15230
  });
14529
15231
  print(` ✓ ${sess.branch} → ${trunk} @ ${sha}${sess.issues.length ? ' (' + sess.issues.map((n) => '#' + n).join(' ') + ')' : ''}`);
15232
+ 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)`);
14530
15233
  }
14531
15234
 
14532
15235
  // ---------------------------------------------------------------------------
@@ -14991,11 +15694,17 @@ its head, trunk runs say when a landing was pushed and when its trunk-CI cycle e
14991
15694
  Reports:
14992
15695
  batches landed, and their fill · combined-run builds: first-attempt green, green after the
14993
15696
  one re-run, red, pending
14994
- red red builds, and how many of their members then landed serially (the fallback)
15697
+ red red builds, and how many of their members then landed alone — serially, or as a
15698
+ batch of one (#580) — the fallback
14995
15699
  dropped members dropped at build, by class, and the eviction rate
14996
15700
  serial serial landings, and MISSED PARTNERS — another change, landed later, that was
14997
15701
  already green when this one landed alone (could have joined) or went green inside
14998
- this landing's trunk-CI cycle (a near miss; its wait is what ship-batch-wait buys)
15702
+ this landing's trunk-CI cycle (a near miss; its wait is what ship-batch-wait buys).
15703
+ "serial" means landed through the serial path, and only that
15704
+ alone the same partner scan over every change that landed ALONE — serially or as a batch
15705
+ of one (#580). On a ship-batch repo a lone ready candidate lands as a fill-1 batch,
15706
+ so there serial reads zero either way; alone is the line to tune ship-batch-wait by.
15707
+ Printed only when a batch of one landed (otherwise it equals serial)
14999
15708
  queue wait green-at-head → landing, per landed change
15000
15709
 
15001
15710
  No batch history in the window is an answer, not an error: it says so, and still reports the
@@ -15014,6 +15723,9 @@ function batchStatsSince(v, nowMs) {
15014
15723
  return Number.isFinite(t) ? t : null;
15015
15724
  }
15016
15725
 
15726
+ /** The trunk log read's buffer (#585); COLAB_BATCH_STATS_MAX_BUFFER overrides it, for a test. */
15727
+ const BATCH_STATS_LOG_MAX_BUFFER = Number(process.env.COLAB_BATCH_STATS_MAX_BUFFER) || 256 * 1024 * 1024;
15728
+
15017
15729
  function cmdBatchStats(argv) {
15018
15730
  const opts = parseArgs(argv, {
15019
15731
  values: { '--repo': 'repo', '--since': 'since' },
@@ -15034,7 +15746,11 @@ function cmdBatchStats(argv) {
15034
15746
  const remote = git.remoteFor(repoAbs);
15035
15747
  const f = git.git(['fetch', remote, trunk], repoAbs);
15036
15748
  if (!f.ok) notes.push(`could not fetch ${remote}/${trunk} (${git.gitFailureLine(f.stderr)}) — read from the local copy, which may be behind`);
15037
- const log = git.git(['log', `${remote}/${trunk}`, '--first-parent', `--since=${sinceIso}`, '--format=%H%x1f%cI%x1f%B%x1e'], repoAbs);
15749
+ // Full squash bodies over a long window pass spawnSync's 1 MiB default (measured 2026-10-10:
15750
+ // 60 days of one repo's trunk came to 1,061,950 bytes), and ENOBUFS then read as a failed
15751
+ // fetch (#585). The buffer is sized for the read; a spawn error is reported as itself.
15752
+ const log = git.git(['log', `${remote}/${trunk}`, '--first-parent', `--since=${sinceIso}`, '--format=%H%x1f%cI%x1f%B%x1e'], repoAbs, { maxBuffer: BATCH_STATS_LOG_MAX_BUFFER });
15753
+ if (!log.ok && log.error) throw new UserError(`could not read ${remote}/${trunk}: ${git.gitFailureLine(log.stderr)} — pass a shorter --since, then run \`colab batch-stats\` again`);
15038
15754
  if (!log.ok) throw new UserError(`could not read ${remote}/${trunk}: ${git.gitFailureLine(log.stderr)} — run \`git fetch ${remote} ${trunk}\`, then run this again`);
15039
15755
  const commits = log.stdout.split('\x1e').map((r) => r.replace(/^\n/, '')).filter((r) => r.trim()).map((r) => {
15040
15756
  const [sha, iso, body] = r.split('\x1f');
@@ -15100,12 +15816,17 @@ function cmdBatchStats(argv) {
15100
15816
  else {
15101
15817
  const fill = Object.keys(rep.batches.fill).sort().map((k) => `${rep.batches.fill[k]}×${k}`).join(' · ') || '—';
15102
15818
  print(` batches ${rep.batches.landed} landed (fill ${fill}) · ${rep.batches.builds} combined-run build(s): ${rep.batches.firstAttemptGreen} first-attempt green (${pct(rep.batches.firstAttemptGreenRate)}), ${rep.batches.greenAfterRerun} after a re-run, ${rep.batches.red} red, ${rep.batches.pending} pending`);
15103
- print(` red ${rep.red.builds} build(s) · ${rep.red.members} member(s), ${rep.red.relandedSerially} then landed serially`);
15819
+ print(` red ${rep.red.builds} build(s) · ${rep.red.members} member(s), ${rep.red.relandedAlone} then landed alone (${rep.red.relandedSerially} serially · ${rep.red.relandedAlone - rep.red.relandedSerially} as a batch of one)`);
15104
15820
  const cls = Object.entries(rep.dropped.byClass).map(([k, v]) => `${v} ${k}`).join(', ');
15105
15821
  print(` dropped ${rep.dropped.count} of ${rep.dropped.attempted} attempted (${pct(rep.dropped.rate)})${cls ? ` — ${cls}` : ''}`);
15106
15822
  }
15107
15823
  print(` serial ${rep.serial.landings} landed alone · ${rep.serial.withMissedPartner} with a missed partner (already green) · ${rep.serial.withNearMiss} more with a near miss (green within its trunk-CI cycle)`);
15108
15824
  if (rep.serial.nearMissWait.samples) print(` near misses per pair, the wait from the lone change's own green that would have caught its partner: ${q(rep.serial.nearMissWait)}`);
15825
+ if (rep.alone.batchOfOne) {
15826
+ // #580: a batch of one landed alone too — the serial line above cannot see it.
15827
+ print(` alone ${rep.alone.landings} landed alone (${rep.alone.landings - rep.alone.batchOfOne} serial · ${rep.alone.batchOfOne} batch of one) · ${rep.alone.withMissedPartner} with a missed partner (already green) · ${rep.alone.withNearMiss} more with a near miss`);
15828
+ if (rep.alone.nearMissWait.samples) print(` near misses (alone) ${q(rep.alone.nearMissWait)}`);
15829
+ }
15109
15830
  print(` queue wait green-at-head → landing: ${q(rep.queueWait)}`);
15110
15831
  for (const n of rep.notes) print(` ! ${n}`);
15111
15832
  return 0;
@@ -15362,6 +16083,63 @@ Empty output is clean ground ONLY when the fetch succeeded. Exit: 0 answered, 2
15362
16083
  staleness (fetch skipped or failed, and the result would have been "clean").
15363
16084
  `;
15364
16085
 
16086
+ const HELP_INSTRUCTION_FILES = `colab instruction-files [--base <rev> | --staged] [--repo <path>] [--json]
16087
+
16088
+ Is every tracked CLAUDE.md the thin-shell shape — the \`@AGENTS.md\` import plus tool-managed blocks,
16089
+ with the repo's prose in AGENTS.md (CONVENTIONS.md §9 step 5, #588)? One judgement
16090
+ (tools/lib/instruction-file.js), shared with the audit, the pre-commit hook and the reusable CI
16091
+ workflow \`.github/workflows/instruction-files.yml\`.
16092
+
16093
+ --base <rev> RATCHET against merge-base(<rev>, HEAD). Fails only when a CLAUDE.md does not
16094
+ conform at HEAD AND either a CLAUDE.md/AGENTS.md changed since the merge base, or
16095
+ every CLAUDE.md conformed there. An unmigrated repo whose change leaves both files
16096
+ alone passes. This is what CI runs.
16097
+ --staged judge the INDEX against HEAD, same ratchet (staging a CLAUDE.md/AGENTS.md is
16098
+ touching it). This is what the pre-commit hook runs.
16099
+ (neither) judge every CLAUDE.md at HEAD, no ratchet: any non-conforming file fails.
16100
+ --repo <path> repo to run in (default: cwd)
16101
+ --json { ok, error?, mode, base, fail, reason, files: [{ path, conforming, message }], changed }
16102
+
16103
+ A fork whose CLAUDE.md/AGENTS.md belong to its upstream declares \`instruction-files: upstream\` in
16104
+ .github/project.yml (read on the judged side — HEAD, the index or the working tree): nothing is judged
16105
+ and the verdict is a pass (\`--json\`: \`exempt: "upstream"\`) — CONVENTIONS.md §9 "A fork of an upstream", #602.
16106
+
16107
+ Exit: 0 pass · 1 fail · 2 cannot judge (not a repo, base not fetched — never read as a pass).
16108
+ The fix for a failure is always the same: move the prose to AGENTS.md (handbook-sync's graft step
16109
+ does the move), keeping CLAUDE.md to \`@AGENTS.md\`, blank lines and tool blocks.
16110
+ `;
16111
+
16112
+ function cmdInstructionFiles(argv) {
16113
+ const opts = parseArgs(argv, {
16114
+ values: { '--repo': 'repo', '--base': 'base' },
16115
+ flags: { '--json': 'json', '--staged': 'staged', '-h': 'help', '--help': 'help' },
16116
+ });
16117
+ if (opts.help) return print(HELP_INSTRUCTION_FILES);
16118
+ if (opts.staged && opts.base) throw new UserError('--staged and --base are two different questions — pass one: `colab instruction-files --staged` (a commit) or `colab instruction-files --base <rev>` (a branch)');
16119
+ // The tree you stand in, NOT resolveRepo's main checkout: from inside a linked worktree the hook
16120
+ // and CI must judge that worktree's index and HEAD, never trunk's.
16121
+ const at = opts.repo ? path.resolve(String(opts.repo)) : process.cwd();
16122
+ const cwd = git.repoRoot(at);
16123
+ if (!cwd) throw new UserError(`${at} is not inside a git repo — pass --repo <path>`);
16124
+ const r = instructionGate.gate({ cwd, staged: !!opts.staged, base: opts.base ? String(opts.base) : null });
16125
+ if (opts.json) {
16126
+ print(JSON.stringify(r, null, 2));
16127
+ return !r.ok ? 2 : r.fail ? 1 : 0;
16128
+ }
16129
+ const lines = instructionGate.describe(r);
16130
+ if (!r.ok) {
16131
+ process.stderr.write(`✗ instruction-files: ${lines[0]} — re-run once the base is fetched (\`git fetch origin\`), or run \`colab instruction-files\` with no --base to judge without the ratchet\n`);
16132
+ return 2;
16133
+ }
16134
+ if (r.fail) {
16135
+ process.stderr.write(`✗ instruction-files: CLAUDE.md carries repo prose — move it to AGENTS.md (\`colab instruction-files --help\`)\n`);
16136
+ for (const l of lines) process.stderr.write(` ${l}\n`);
16137
+ return 1;
16138
+ }
16139
+ for (const l of lines) print(r.bad.length ? `! ${l}` : `✓ ${l}`);
16140
+ return 0;
16141
+ }
16142
+
15365
16143
  function cmdHolders(argv) {
15366
16144
  const opts = parseArgs(argv, {
15367
16145
  values: { '--repo': 'repo', '--base': 'base' },
@@ -15992,6 +16770,8 @@ Commands:
15992
16770
  blocked <blocked> --by <blocker> [--clear --reason R [--force]] [--repo P]
15993
16771
  own the blocked_by dependency-edge write (#251)
15994
16772
  migration-grant <issue> --branch B | --revoke | --list [--json] human-only ship migration exemption (#98)
16773
+ owner-policy [show [--json]] the retired owner-level grant policy (#596), read-only;
16774
+ set refuses — use config set migration-grant (#598)
15995
16775
  decision <issue> --record --ruled-by N | --reopen --ruled-by N | --list [--json]
15996
16776
  record/reopen a needs-decision answer (#121, #122)
15997
16777
  ci-grant <issue> --branch B | --revoke | --list [--json] ship trunk-CI-green exemption: human, or ci-reviewer under opt-in (#105, #504)
@@ -16028,6 +16808,10 @@ Commands:
16028
16808
  holders <path> [--base B] [--json] who else is holding <path> — refs that touched it and
16029
16809
  have not landed on the base (filters the raw git-log
16030
16810
  one-liner through \`landed\`'s content classification)
16811
+ instruction-files [--base B | --staged] [--json]
16812
+ CLAUDE.md is only @AGENTS.md + tool blocks? ratcheted:
16813
+ fails only where the change touches it or would regress
16814
+ a migrated repo (#588) — the hook and CI run this
16031
16815
  promote [--repo P] [--message M] [--dry] trunk → main (--no-ff); gated by deploy + promotion; never tags
16032
16816
  deliver [--repo P] [--dry] [--json] [--reopen] project.yml owner: only — open/refresh ONE PR
16033
16817
  trunk → the owner's branch; never merges it (#394)
@@ -16100,6 +16884,7 @@ function main(argv) {
16100
16884
  case 'readiness': return cmdReadiness(rest);
16101
16885
  case 'blocked': return cmdBlocked(rest);
16102
16886
  case 'migration-grant': return cmdMigrationGrant(rest);
16887
+ case 'owner-policy': return cmdOwnerPolicy(rest);
16103
16888
  case 'decision': return cmdDecision(rest);
16104
16889
  case 'ci-grant': return cmdCiGrant(rest);
16105
16890
  case 'claims': return cmdClaims(rest);
@@ -16115,6 +16900,7 @@ function main(argv) {
16115
16900
  case 'trunk-ci': return cmdTrunkCi(rest);
16116
16901
  case 'ci-wait': return cmdCiWait(rest);
16117
16902
  case 'holders': return cmdHolders(rest);
16903
+ case 'instruction-files': return cmdInstructionFiles(rest);
16118
16904
  case 'promote': return cmdPromote(rest);
16119
16905
  case 'deliver': return cmdDeliver(rest);
16120
16906
  case 'doctor': return cmdDoctor(rest);