@futurelastic/colab-handbook 1.12.0 → 1.13.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 (74) hide show
  1. package/README.md +248 -213
  2. package/README.vi.md +252 -186
  3. package/audit/audit.mjs +193 -10
  4. package/package.json +7 -1
  5. package/templates/README.md +30 -2
  6. package/templates/ci-laravel.yml +102 -21
  7. package/templates/ci-node.yml +61 -3
  8. package/templates/ci-python.yml +52 -3
  9. package/templates/deploy-adapter-portainer.mjs +206 -0
  10. package/templates/deploy-container-run.mjs +368 -0
  11. package/templates/deploy-container.yml +219 -0
  12. package/templates/dist-refs.yml +6 -0
  13. package/templates/docs-lint.mjs +1 -1
  14. package/templates/npx-launcher.mjs +118 -20
  15. package/templates/npx-service.mjs +828 -0
  16. package/templates/release-auto.yml +341 -32
  17. package/tools/colab +1902 -278
  18. package/tools/lib/adopt.js +373 -14
  19. package/tools/lib/branch-name.js +29 -1
  20. package/tools/lib/ci-cure.js +522 -31
  21. package/tools/lib/ci-grant.js +289 -22
  22. package/tools/lib/ci-wait.js +223 -0
  23. package/tools/lib/claim-comments.js +13 -64
  24. package/tools/lib/claim-identity.js +42 -7
  25. package/tools/lib/codec/claim.d.ts +41 -0
  26. package/tools/lib/codec/claim.js +153 -0
  27. package/tools/lib/codec/decision.d.ts +29 -0
  28. package/tools/lib/codec/decision.js +81 -0
  29. package/tools/lib/codec/grants.d.ts +82 -0
  30. package/tools/lib/codec/grants.js +268 -0
  31. package/tools/lib/codec/hold.d.ts +26 -0
  32. package/tools/lib/codec/hold.js +152 -0
  33. package/tools/lib/codec/index.d.ts +21 -0
  34. package/tools/lib/codec/index.js +32 -0
  35. package/tools/lib/codec/labels.d.ts +65 -0
  36. package/tools/lib/codec/labels.js +723 -0
  37. package/tools/lib/codec/markers.d.ts +35 -0
  38. package/tools/lib/codec/markers.js +138 -0
  39. package/tools/lib/codec/release.d.ts +17 -0
  40. package/tools/lib/codec/release.js +69 -0
  41. package/tools/lib/codec/samples.json +778 -0
  42. package/tools/lib/codeowners.js +68 -4
  43. package/tools/lib/container-close.js +38 -0
  44. package/tools/lib/cure-diff.js +198 -9
  45. package/tools/lib/decision-record.js +15 -39
  46. package/tools/lib/docs-only.js +15 -1
  47. package/tools/lib/exposure-shape.js +42 -8
  48. package/tools/lib/git.js +324 -42
  49. package/tools/lib/group-labels.js +65 -0
  50. package/tools/lib/install-check.js +14 -8
  51. package/tools/lib/install-route.js +139 -0
  52. package/tools/lib/instruction-file.js +1 -0
  53. package/tools/lib/labels.js +22 -647
  54. package/tools/lib/local-adopt.js +8 -4
  55. package/tools/lib/migration-grant.js +206 -104
  56. package/tools/lib/place.js +2 -2
  57. package/tools/lib/release-cut.js +199 -25
  58. package/tools/lib/release-finalize.js +111 -23
  59. package/tools/lib/release-policy.js +130 -22
  60. package/tools/lib/release-runner.js +125 -0
  61. package/tools/lib/release-tag.js +3 -1
  62. package/tools/lib/scratch-dirs.js +118 -0
  63. package/tools/lib/ship-batch.js +36 -1
  64. package/tools/lib/ship-human-door.js +76 -0
  65. package/tools/lib/stamp.js +7 -0
  66. package/tools/lib/tracker-fake.js +195 -0
  67. package/tools/lib/tracker-github.js +106 -0
  68. package/tools/lib/tracker-scenarios.json +206 -0
  69. package/tools/lib/tracker.js +64 -0
  70. package/tools/lib/tree-green.js +88 -0
  71. package/tools/lib/util.js +17 -1
  72. package/tools/lib/verify-runs.js +104 -0
  73. package/tools/lib/wake.js +8 -90
  74. package/tools/lib/workflow-triggers.js +48 -0
package/tools/colab CHANGED
@@ -15,6 +15,7 @@ const { spawnSync } = require('child_process');
15
15
 
16
16
  const state = require('./lib/state');
17
17
  const git = require('./lib/git');
18
+ const tracker = require('./lib/tracker'); // every gh call goes through tracker-github.js (#500)
18
19
  const ports = require('./lib/ports');
19
20
  const stamp = require('./lib/stamp');
20
21
  const releaseTag = require('./lib/release-tag');
@@ -45,8 +46,12 @@ const trustHumans = require('./lib/trust-humans');
45
46
  const ciCure = require('./lib/ci-cure');
46
47
  const ciVerdict = require('./lib/ci-verdict');
47
48
  const baseCiVerdict = require('./lib/base-ci-verdict');
49
+ const treeGreen = require('./lib/tree-green');
50
+ const verifyRuns = require('./lib/verify-runs');
51
+ const ciWait = require('./lib/ci-wait'); // #495
48
52
  const staleBase = require('./lib/stale-base');
49
53
  const dirtyOwner = require('./lib/dirty-owner');
54
+ const scratchDirs = require('./lib/scratch-dirs');
50
55
  const lockfileDrift = require('./lib/lockfile-drift');
51
56
  const adopt = require('./lib/adopt');
52
57
  const consumerEvidence = require('./lib/consumer-evidence');
@@ -54,6 +59,7 @@ const axisAuthority = require('./lib/axis-authority');
54
59
  const writesAuthority = require('./lib/writes-authority');
55
60
  const claimIdentity = require('./lib/claim-identity');
56
61
  const claimComments = require('./lib/claim-comments');
62
+ const codec = require('./lib/codec');
57
63
  const machine = require('./lib/machine');
58
64
  const targetSync = require('./lib/ship-target-sync');
59
65
  const shipBatch = require('./lib/ship-batch');
@@ -71,6 +77,7 @@ const shipRoles = require('./lib/ship-roles'); // #372
71
77
  const refsBrake = require('./lib/refs-brake'); // #385
72
78
  const localAdopt = require('./lib/local-adopt'); // #393
73
79
  const ownerBranch = require('./lib/owner-branch'); // #394
80
+ const humanDoor = require('./lib/ship-human-door'); // #525
74
81
  const {
75
82
  HOST, UserError, normIssueNum, issueTag, claimKey, today, nowISO, hoursSince, humanAge,
76
83
  parseArgs, table, shortRepo,
@@ -129,7 +136,8 @@ function resolveRepo(opts) {
129
136
  * `.github/project.yml` into the main checkout when run from inside a worktree it was supposed
130
137
  * to target — silently violating "the main checkout stays on trunk at rest" (#258). This
131
138
  * mirrors the `opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null)` pattern
132
- * already used at most other cmd* call sites, as a named, reusable resolver.
139
+ * once used at most other cmd* call sites (normalised since #487 — resolveRepoOrCwd), as a named,
140
+ * reusable resolver for the one question that genuinely wants the caller's own tree.
133
141
  */
134
142
  function resolveWorkingRepo(opts) {
135
143
  let r = opts.repo;
@@ -154,16 +162,60 @@ function knownRepos(config) {
154
162
  return extra;
155
163
  }
156
164
 
157
- /** Find a single claim by issue number, optionally constrained to a repo. */
165
+ /**
166
+ * The repo a lookup with no --repo is about: --repo (normalised) or the MAIN root of cwd, or null.
167
+ *
168
+ * #487: this used to be spelled `resolveRepoOrCwd(opts)`
169
+ * at a dozen call sites — normalised with --repo, NOT normalised without it. Run from inside a
170
+ * linked worktree, the bare form answered with the worktree's own root, so a release looked up
171
+ * `<worktree>#N` while the claim sat under `<mainRoot>#N`. Every one of those sites is about repo
172
+ * STATE or the tracker (claims, ports, grants, events), never a committable file — for that,
173
+ * resolveWorkingRepo() is the deliberate exception.
174
+ */
175
+ function resolveRepoOrCwd(opts) {
176
+ return opts.repo ? resolveRepo(opts) : (git.mainRepoRoot(process.cwd()) || null);
177
+ }
178
+
179
+ /**
180
+ * The main checkout a claim row belongs to, given the path in its key (or its `repo` field).
181
+ *
182
+ * #487: an older writer (`claims --sync` run from inside a linked worktree) keyed rows by the
183
+ * WORKTREE's path. Those rows outlive the worktree, and the path no longer exists, so nothing could
184
+ * resolve it back to its repo — `release` missed them with and without --repo, forever. A path that
185
+ * exists resolves through git; a vanished one is attributed to the nearest existing ancestor's main
186
+ * root, but only when that ancestor IS a repo the path sits inside — never a guess across repos.
187
+ */
188
+ function claimHomeRoot(p) {
189
+ if (!p) return p;
190
+ if (fs.existsSync(p)) return git.mainRepoRoot(p) || p;
191
+ let dir = path.dirname(p);
192
+ while (dir && dir !== path.dirname(dir) && !fs.existsSync(dir)) dir = path.dirname(dir);
193
+ const root = dir && fs.existsSync(dir) ? git.mainRepoRoot(dir) : null;
194
+ return root && p.startsWith(`${root}${path.sep}`) ? root : p;
195
+ }
196
+
197
+ /** Does the claim key `k` belong to `repoAbs` (a main root)? Includes legacy worktree-keyed rows (#487). */
198
+ function claimKeyInRepo(k, repoAbs) {
199
+ if (k.startsWith(`${repoAbs}#`)) return true;
200
+ const keyPath = k.slice(0, k.lastIndexOf('#'));
201
+ return keyPath.startsWith(`${repoAbs}${path.sep}`) && claimHomeRoot(keyPath) === repoAbs;
202
+ }
203
+
204
+ /**
205
+ * Find a single claim by issue number, optionally constrained to a repo. `repo` in the result is
206
+ * the claim's MAIN root — for a legacy worktree-keyed row (#487) that is not `claim.repo`, which
207
+ * names a directory that may no longer exist; anything talking to the tracker must use `repo`.
208
+ */
158
209
  function findClaim(st, num, repoAbs) {
159
210
  const matches = Object.entries(st.claims).filter(([, c]) => normIssueNum(c.issue) === num);
160
- const scoped = repoAbs ? matches.filter(([k]) => k.startsWith(`${repoAbs}#`)) : matches;
211
+ const scoped = repoAbs ? matches.filter(([k]) => claimKeyInRepo(k, repoAbs)) : matches;
161
212
  if (scoped.length === 0) return null;
162
213
  if (scoped.length > 1) {
163
- const repos = scoped.map(([k]) => shortRepo(k.split('#')[0])).join(', ');
214
+ const repos = scoped.map(([k]) => shortRepo(k.slice(0, k.lastIndexOf('#')))).join(', ');
164
215
  throw new UserError(`Issue #${num} is claimed in multiple repos (${repos}) — disambiguate with --repo`);
165
216
  }
166
- return { key: scoped[0][0], claim: scoped[0][1] };
217
+ const [key, claim] = scoped[0];
218
+ return { key, claim, repo: repoAbs || claimHomeRoot(claim.repo || key.slice(0, key.lastIndexOf('#'))) };
167
219
  }
168
220
 
169
221
  function isGhUsable(repoAbs) {
@@ -177,7 +229,12 @@ function isGhUsable(repoAbs) {
177
229
  */
178
230
  function ghUnusableWhy(repoAbs) {
179
231
  const s = git.ghState();
180
- if (!s.ok) return s.reason === 'missing' ? 'gh is not installed' : 'gh has no working credential — `gh api user` fails';
232
+ if (!s.ok && s.reason === 'missing') return 'gh is not installed';
233
+ if (!s.ok && s.reason === 'rate-limited') { // #516
234
+ const until = s.resetAt ? ` until ${new Date(s.resetAt).toISOString().replace(/\.\d{3}Z$/, 'Z')}` : '';
235
+ return `gh credential is rate-limited${until} — not a credential problem: wait for the reset, or switch account`;
236
+ }
237
+ if (!s.ok) return 'gh has no working credential — `gh api user` fails';
181
238
  const rp = git.remoteProblem(git.remoteInfo(repoAbs)); // #301: ambiguous remotes / a broken colab.remote
182
239
  if (rp) return rp;
183
240
  if (!git.remoteUrl(repoAbs)) return 'no origin remote';
@@ -195,9 +252,10 @@ function ghUnusableWhy(repoAbs) {
195
252
  // GitHub offers no atomic check-and-set on labels/assignees.
196
253
  // ---------------------------------------------------------------------------
197
254
 
198
- // The claim/release comment markers and parsers live in tools/lib/claim-comments.js (#369/#375) —
255
+ // The claim/release comment markers and their encode/decode pairs live in tools/lib/codec/claim.js
256
+ // (#497); the readers built on them (liveness, tie-break) in tools/lib/claim-comments.js (#369/#375) —
199
257
  // a STABLE WIRE FORMAT the refusal path, the tie-break and dashboards grep. Do not reword casually.
200
- const { CLAIM_MARK, RELEASE_MARK, liveClaimComments, tieBreakVerdict } = claimComments;
258
+ const { liveClaimComments, tieBreakVerdict } = claimComments; // the format itself: codec/claim.js (#497)
201
259
 
202
260
  /**
203
261
  * #369: may a comment colab posts to THIS repo's tracker name the host in its `host` field? The
@@ -226,11 +284,38 @@ function myMachineId() { return machine.localMachine().id || null; }
226
284
 
227
285
  /**
228
286
  * Resolve the Claude session URL for this invocation: --session flag > COLAB_SESSION env >
229
- * '' (absent, never an error). Free-form — typically a session URL.
287
+ * a DERIVED person identity (#528) > '' (absent, never an error). Free-form — typically a session URL.
288
+ *
289
+ * The derived step exists for a person at a plain terminal, who has no session runtime and so no
290
+ * id to pass: without it their first trunk `colab claim` refused (#242's gate), `worktree new`
291
+ * warned three lines every time, and ship evidence read `implemented by: unknown`. It applies only
292
+ * when `COLAB_SESSION` is unset and the shell is not an agent's (`claimIdentity.
293
+ * shouldDerivePersonSession` has why) — an explicit flag or env value always wins.
230
294
  */
231
295
  function resolveSession(opts) {
232
- const s = opts.session || process.env.COLAB_SESSION || '';
233
- return String(s).trim();
296
+ const s = String(opts.session || process.env.COLAB_SESSION || '').trim();
297
+ return s || derivedPersonSession();
298
+ }
299
+
300
+ /**
301
+ * The derived person identity for this invocation, or ''. Memoized — one `git config` spawn, and
302
+ * the "derived" note is printed once per invocation (stderr, so `--json` stdout stays clean).
303
+ */
304
+ let derivedSessionCache = null;
305
+ function derivedPersonSession() {
306
+ if (derivedSessionCache !== null) return derivedSessionCache;
307
+ derivedSessionCache = '';
308
+ if (!claimIdentity.shouldDerivePersonSession(process.env)) return derivedSessionCache;
309
+ const r = spawnSync('git', ['config', '--get', 'user.email'], { encoding: 'utf8' });
310
+ const email = r.status === 0 ? String(r.stdout || '').trim() : '';
311
+ let user = process.env.USER || '';
312
+ if (!user) { try { user = os.userInfo().username; } catch { user = ''; } }
313
+ derivedSessionCache = claimIdentity.derivePersonSession({ email, user, hostToken: machine.hostToken(HOST) });
314
+ if (derivedSessionCache) {
315
+ process.stderr.write(`· session: ${derivedSessionCache} (derived — no --session or COLAB_SESSION given; ` +
316
+ `either one overrides it)\n`);
317
+ }
318
+ return derivedSessionCache;
234
319
  }
235
320
 
236
321
  /**
@@ -388,14 +473,6 @@ function identityLegend(entries) {
388
473
  print(' Repair: colab worktree tag <worktree> --session <url>');
389
474
  }
390
475
 
391
- /** The ` · session …` comment suffix, or '' — keeps the no-identity comment byte-stable. */
392
- function sessionCommentSuffix(session, sessionName) {
393
- if (sessionName && session) return ` · session [${sessionName}](${session})`; // both → markdown link
394
- if (session) return ` · session ${session}`; // url only → legacy form
395
- if (sessionName) return ` · session ${sessionName}`; // name only
396
- return '';
397
- }
398
-
399
476
  /**
400
477
  * Worktree lifecycle status, backfilled-on-read: entries created before this field existed (or by
401
478
  * an older colab) render as `running`. Values: `running` (default, at create) → `merged` (branch
@@ -404,17 +481,18 @@ function sessionCommentSuffix(session, sessionName) {
404
481
  */
405
482
  function wtStatus(wt) { return (wt && wt.status) || 'running'; }
406
483
 
407
- /** The exact claim-comment body. Keep in lockstep with CLAIM_RE/parseSessionField and the README. */
484
+ /**
485
+ * The exact claim-comment body. The format itself is codec/claim.js `encodeClaim` (#497); this
486
+ * supplies what the codec deliberately does not hold — the clock and the machine digest. `-` stands
487
+ * for "no branch"/"no worktree" (#53, it used to be the word `trunk`). `host` is the raw hostname
488
+ * where the destination may name it, the `h:` token where it may not (#369, `commentHost`); the
489
+ * comparable identity is the machine digest beside it (#327), omitted when no id resolved.
490
+ */
408
491
  function claimCommentBody(wtName, branch, session, sessionName, host = HOST) {
409
- // `-` for "no branch", matching the worktree field beside it. It used to be the word `trunk`,
410
- // which read as a branch name that never existed (#53).
411
- const base = `${CLAIM_MARK} — worktree \`${wtName || '-'}\` · branch \`${branch || '-'}\` · host \`${host}\` · ${nowISO()}`;
412
- // #327: `host` is the raw hostname where the destination may name it, the `h:` token where it
413
- // may not (#369, `commentHost`); the comparable identity is the machine digest beside it.
414
- // Omitted when no id resolved.
415
- const token = machine.machineToken(myMachineId());
416
- const mach = token ? ` · machine \`${token}\`` : '';
417
- return base + mach + sessionCommentSuffix(session, sessionName);
492
+ return codec.encodeClaim({
493
+ worktree: wtName, branch, host, at: nowISO(),
494
+ machine: machine.machineToken(myMachineId()) || '', session, sessionName,
495
+ });
418
496
  }
419
497
 
420
498
  /** Issues whose EXISTING local claim sits on a different worktree than the one we're claiming onto. */
@@ -470,9 +548,14 @@ function remoteClaimConflicts(st, repoAbs, nums) {
470
548
  const want = new Set(nums);
471
549
  const records = [...Object.values(st.worktrees || {}), ...Object.values(st.claims || {})];
472
550
  const ours = (b) => records.some((r) => r && r.repo === repoAbs && r.branch === b && machine.isLocal(r));
551
+ // #485: a dependabot ref, trunk and every declared integration: line are never a session's claim —
552
+ // their trailing digits are a version or an accident of naming. Same filter as code-sweep §1.3.
553
+ const doc = projectDoc(repoAbs);
554
+ const trunk = resolveTrunk(repoAbs, doc) || '';
555
+ const scope = { trunk, integration: trunk ? resolveIntegration(repoAbs, doc, trunk) : [] };
473
556
  const conflicts = [];
474
557
  for (const h of heads.heads) {
475
- const carried = shipguard.branchIssueNumbers(h.branch).filter((n) => want.has(n));
558
+ const carried = branchName.claimIssueNumbers(h.branch, scope).filter((n) => want.has(n));
476
559
  if (!carried.length || ours(h.branch)) continue;
477
560
  for (const num of carried) conflicts.push({ num, remote, branch: h.branch, sha: h.sha });
478
561
  }
@@ -663,7 +746,7 @@ function postClaimComment(repoAbs, num, wtName, branch, session, sessionName) {
663
746
  function postReleaseComment(repoAbs, num) {
664
747
  const info = git.ghIssueView(repoAbs, num, ['state']);
665
748
  if (info && info.state === 'CLOSED') return true; // don't chatter on a closed issue
666
- const r = git.ghIssueComment(repoAbs, num, RELEASE_MARK);
749
+ const r = git.ghIssueComment(repoAbs, num, codec.encodeRelease());
667
750
  if (!r.ok) { warnDeferred(`could not post release comment on #${num} (${r.stderr.split('\n')[0] || r.code})`); return false; }
668
751
  return true;
669
752
  }
@@ -1208,8 +1291,8 @@ Refuses, naming each failed condition (all are reported, not just the first):
1208
1291
  switch-dependencies a colab:switch marker is malformed, or a finished switch needs one that is not
1209
1292
  manifest-version the tag does not equal the version a manifest declares (VERSION, package.json,
1210
1293
  Cargo.toml [package], pyproject.toml [project]/[tool.poetry]) — none declared
1211
- passes: the tag is the version (#424). With release.version-source: tag (#438)
1212
- a differing manifest is DERIVABLE — skipped, named in the tag message, and
1294
+ passes: the tag is the version (#424). Under release.version-source: tag (#438;
1295
+ the default where the machine cuts the tag, #484) a differing manifest is DERIVABLE — skipped, named in the tag message, and
1213
1296
  stamped from the tag by the repo's own release step (never on trunk)
1214
1297
  on-trunk the commit is not an ancestor of main, or the checkout is shallow (#424)
1215
1298
  outranks-final the version is not strictly greater than the highest final tag (#424)
@@ -1235,6 +1318,20 @@ Refuses, naming each failed condition (all are reported, not just the first):
1235
1318
  There the bump reads the promoted commits (main's merge subject is skipped),
1236
1319
  and a switch-removal child counts when its Closes #N was promoted.
1237
1320
 
1321
+ Route deploy-tag-fast (#446) — a deploy: tag repo with the operator's grant and a declared health gate:
1322
+ --auto tags the FINAL vX.Y.Z on main's green head — no candidate, no test period — publishes it as
1323
+ the latest GitHub Release, moves the stable channel, and prints final/deploy in --json so the
1324
+ release workflow's deploy job deploys it in the same run. Without --auto it refuses: a final cut by
1325
+ hand would reach production with no deploy job behind it. Five more conditions there:
1326
+ spacing release.final-spacing (default and floor 1h) since the newest final — inside
1327
+ it the run is a NO-OP; the first run after it tags main's head
1328
+ already-final main's head already carries a final — a NO-OP
1329
+ final-grant release.final-grant's decision still resolves (recorded, trusted, not reopened)
1330
+ release-hold an open issue carries the release-hold label (a human veto)
1331
+ migration-grant a migration since the last final with no grant on the version's tracking
1332
+ issue — refused; a non-dry run opens "release: vX.Y.Z" if needed and posts the
1333
+ one human command (COLAB_HUMAN=1 colab migration-grant <N> --branch vX.Y.Z)
1334
+
1238
1335
  The bump (without --auto) is release-status's semverSuggestion since the last final tag (candidates skipped): fix ->
1239
1336
  patch, feat -> minor; a breaking change is a minor pre-1.0 and a refusal from 1.0 on.
1240
1337
  --bump patch|minor override the computed bump — requires --reason, which is recorded on the tag
@@ -1261,16 +1358,13 @@ no-op; 1 when refused.
1261
1358
  function readAllIssuesForSwitches(repoAbs) {
1262
1359
  const LIMIT = 5000;
1263
1360
  // title/labels/createdAt/url are additive (#339): `release finalize` finds its tracking issue in the same read.
1264
- const r = spawnSync('gh', ['issue', 'list', '--state', 'all', '--limit', String(LIMIT), '--json', 'number,state,stateReason,body,title,labels,createdAt,closedAt,url'],
1265
- { cwd: repoAbs, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 });
1266
- if (r.status !== 0) return null;
1267
- try {
1268
- const list = JSON.parse(r.stdout);
1269
- // A full page may be a truncated one — an unread marker is not a cleared one.
1270
- return Array.isArray(list) && list.length < LIMIT ? list : null;
1271
- } catch (_) {
1272
- return null;
1273
- }
1361
+ const r = tracker.forRepo(repoAbs).issueListAll({
1362
+ limit: LIMIT, fields: ['number', 'state', 'stateReason', 'body', 'title', 'labels', 'createdAt', 'closedAt', 'url'],
1363
+ maxBuffer: 512 * 1024 * 1024,
1364
+ });
1365
+ const list = r.data; // null: the read failed or was unparseable
1366
+ // A full page may be a truncated one — an unread marker is not a cleared one.
1367
+ return Array.isArray(list) && list.length < LIMIT ? list : null;
1274
1368
  }
1275
1369
 
1276
1370
  /** [{status, path, content}] for every path changed between `from` (null = the empty tree) and `sha`; null on a git failure. */
@@ -1310,7 +1404,7 @@ function measureCandidateConditions(repoAbs, { sha, lastFinal, at, readRuns, iss
1310
1404
  const why = ghUnusableWhy(repoAbs);
1311
1405
  ci = { ok: false, detail: `gh not usable (${why}) — cannot confirm CI at ${at}` };
1312
1406
  suite = { ok: false, detail: `gh not usable (${why}) — cannot confirm the suite ran at ${at}` };
1313
- switches = { ok: false, detail: `gh not usable (${why}) — the colab:switch markers cannot be read` };
1407
+ switches = { ok: false, unread: true, detail: `gh not usable (${why}) — the colab:switch markers cannot be read` };
1314
1408
  } else {
1315
1409
  const rows = readRuns();
1316
1410
  const run = git.summarizeRunsForCommit(rows, sha);
@@ -1326,7 +1420,7 @@ function measureCandidateConditions(repoAbs, { sha, lastFinal, at, readRuns, iss
1326
1420
  const declared = migrationPaths.unionPaths(projectDoc(repoAbs), projectDocAt(repoAbs, sha));
1327
1421
  const changes = releaseCutChanges(repoAbs, lastFinal, sha, declared);
1328
1422
  const schema = changes === null
1329
- ? { ok: false, detail: 'git diff failed — schema changes cannot be read' }
1423
+ ? { ok: false, unread: true, detail: 'git diff failed — schema changes cannot be read' }
1330
1424
  : releaseCut.schemaVerdict(changes, lastFinal || 'the first commit', declared);
1331
1425
  // #441: every migration file since the last final, destructive or not — an operator-granted
1332
1426
  // automatic final refuses an ungranted one (release-finalize.js migrationGrantVerdict).
@@ -1441,6 +1535,75 @@ function measureAutoSignals(repoAbs, { doc, sha, lastFinal, remote, issues, trun
1441
1535
  return { signals, migration: (v) => releaseCut.parseMigrationSection(migrationText, v) };
1442
1536
  }
1443
1537
 
1538
+ /** #446: every final `vX.Y.Z` tag as [{ name, date }] — what release.final-spacing counts. A human's final counts too. */
1539
+ function finalTags(repoAbs) {
1540
+ const fe = git.git(['for-each-ref', 'refs/tags', '--format=%(refname:short)%09%(creatordate:iso-strict)'], repoAbs);
1541
+ return (fe.ok ? fe.stdout.split('\n').filter(Boolean) : []).map((l) => l.split('\t'))
1542
+ .filter(([name]) => releaseCut.parseVersion(name)).map(([name, date]) => ({ name, date }));
1543
+ }
1544
+
1545
+ /**
1546
+ * #446: what route deploy-tag-fast keeps in place of a test period, measured — the operator's grant
1547
+ * (the #441 reader, against trunk's trust-humans), the repo-wide release-hold veto, every migration
1548
+ * since the last final against a grant on the computed version's tracking issue, and the spacing
1549
+ * since the newest final. The version is computed here only to find that tracking issue; decide()
1550
+ * computes it again from the same inputs, so the two cannot disagree.
1551
+ */
1552
+ function measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: paths }) {
1553
+ const grantDecl = policy.effective.finalGrant;
1554
+ const trust = trustAt(repoAbs, `${remote}/main`);
1555
+ const finalGrant = isGhUsable(repoAbs)
1556
+ ? releasePolicy.finalGrantVerdict(git.ghIssueView(repoAbs, grantDecl.issue, ['state', 'labels', 'comments']), { issue: grantDecl.issue, trust })
1557
+ : { ok: false, unread: true, ruledBy: null, detail: `release.final-grant #${grantDecl.issue} could not be read: gh not usable (${ghUnusableWhy(repoAbs)})` };
1558
+ const holds = releaseCut.holdsVerdict(issues);
1559
+ let tracking = null;
1560
+ let grant = null;
1561
+ const v = auto ? releaseCut.decideAutoVersion({ lastFinal, signals: auto.signals, migration: auto.migration, tags }) : null;
1562
+ if (v && v.ok && issues) {
1563
+ const open = issues.filter((i) => String(i.state || '').toUpperCase() === 'OPEN' && releaseFinalize.parseReleaseMarker(i.body) === v.version);
1564
+ if (open.length) tracking = { number: open[0].number };
1565
+ }
1566
+ if (paths && paths.length) {
1567
+ grant = tracking
1568
+ ? migrationGrant.evaluateIssue(git.ghIssueView(repoAbs, tracking.number, ['state', 'labels', 'comments']), v.version, tracking.number, labels.MIGRATION_GRANT_LABEL, { trust })
1569
+ : { ok: false, reason: 'no tracking issue yet to carry a grant' };
1570
+ if (grant && grant.ok) grant = { ...grant, issue: tracking.number };
1571
+ }
1572
+ const migrations = { ...releaseFinalize.migrationGrantVerdict({ paths, grant, since: lastFinal }), paths: paths || null };
1573
+ const spacing = releaseCut.spacingVerdict({ finals: finalTags(repoAbs), spacingHours: policy.effective.finalSpacingHours, now: new Date().toISOString() });
1574
+ return { finalGrant, holds, migrations, spacing, tracking };
1575
+ }
1576
+
1577
+ /** Post `text` on issue `num` once — idempotent by release-finalize's event marker. */
1578
+ function commentOnce(repoAbs, num, fields, text) {
1579
+ const view = git.ghIssueView(repoAbs, num, ['comments']);
1580
+ if (view && releaseFinalize.hasEvent(view.comments, fields)) return;
1581
+ const r = git.ghIssueComment(repoAbs, num, `${releaseFinalize.eventMarker(fields)}\n${text}`);
1582
+ if (!r.ok) warn(`could not comment on #${num}: ${String(r.stderr || '').split('\n')[0]}`);
1583
+ }
1584
+
1585
+ /**
1586
+ * #426: one "Released in vX.Y.Z" comment on every issue the version carries — the closing references
1587
+ * in (previous final, sha], minus `exclude` (the release tracking issues). Idempotent by event marker.
1588
+ * Shared by `release finalize` and, on route deploy-tag-fast (#446), `release cut`.
1589
+ */
1590
+ function announceCarried(repoAbs, { tagNames, exclude, version, sha }) {
1591
+ const prev = releaseFinalize.previousFinal(tagNames, version);
1592
+ if (!prev) return { range: null, issues: [], posted: [], skipped: [], detail: 'no previous final — the first version announces nothing' };
1593
+ const log = git.git(['log', '--format=%B%x00', `${prev}..${sha}`], repoAbs);
1594
+ if (!log.ok) { warn(`could not read ${prev}..${shortSha(sha)} — no issue told it was released in ${version}`); return { range: `${prev}..${version}`, issues: [], posted: [], skipped: [], detail: 'git log failed' }; }
1595
+ const nums = releaseFinalize.carriedIssues(log.stdout.split('\0'), { exclude });
1596
+ const posted = []; const skipped = [];
1597
+ for (const n of nums) {
1598
+ const view = git.ghIssueView(repoAbs, n, ['comments']);
1599
+ if (!view) { skipped.push(n); continue; }
1600
+ if (releaseFinalize.hasEvent(view.comments, releaseFinalize.releasedEvent(version))) continue;
1601
+ const r = git.ghIssueComment(repoAbs, n, releaseFinalize.releasedComment(version, sha));
1602
+ if (r.ok) posted.push(n); else { skipped.push(n); warn(`could not comment on #${n}: ${String(r.stderr || '').split('\n')[0]}`); }
1603
+ }
1604
+ return { range: `${prev}..${version}`, issues: nums, posted, skipped };
1605
+ }
1606
+
1444
1607
  function cmdReleaseCut(argv) {
1445
1608
  const opts = parseArgs(argv, {
1446
1609
  values: { '--repo': 'repo', '--bump': 'bump', '--reason': 'reason' },
@@ -1485,7 +1648,7 @@ function cmdReleaseCut(argv) {
1485
1648
  const tags = lines(git.git(['tag', '--list'], repoAbs));
1486
1649
  const tagsAtSha = lines(git.git(['tag', '--points-at', sha], repoAbs));
1487
1650
 
1488
- const { ci, suite, schema, switches, issues } = measureCandidateConditions(repoAbs, {
1651
+ const { ci, suite, schema, switches, issues, migrations: migrationPathsSince } = measureCandidateConditions(repoAbs, {
1489
1652
  sha, lastFinal, at, readRuns: () => releaseCut.withoutOwnWorkflow(git.ghRunsForCommit(repoAbs, 'main', sha)), // #425
1490
1653
  });
1491
1654
  const { manifests, ancestry } = measurePreTag(repoAbs, sha, `${remote}/main`); // #424
@@ -1497,9 +1660,17 @@ function cmdReleaseCut(argv) {
1497
1660
  auto = { signals, migration, cadence, promotion: offTrunk ? measurePromotion(repoAbs, { sha, trunk, remote, fetched: trunkFetch }) : null };
1498
1661
  }
1499
1662
 
1663
+ // #446: route deploy-tag-fast — the grant, the human veto, the migration gate and the spacing are
1664
+ // measured only there, so every candidate route's run is what it was.
1665
+ const fast = releaseCut.isFastRoute(policy) && !policy.findings.length;
1666
+ const fastFacts = fast ? measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: migrationPathsSince }) : {};
1667
+ if (fast && auto) auto.spacing = fastFacts.spacing;
1668
+
1500
1669
  const verdict = releaseCut.decide({
1501
1670
  policy, triggers, lastFinal, suggestion, tags, tagsAtSha, ci, suite, schema, switches, manifests, ancestry, auto,
1502
1671
  override: opts.bump ? { bump: opts.bump, reason: opts.reason } : null,
1672
+ finalGrant: fastFacts.finalGrant, holds: fastFacts.holds, migrations: fastFacts.migrations,
1673
+ trackingIssue: fastFacts.tracking ? fastFacts.tracking.number : null,
1503
1674
  });
1504
1675
 
1505
1676
  let created = false;
@@ -1514,19 +1685,53 @@ function cmdReleaseCut(argv) {
1514
1685
  throw new UserError(`git push ${remote} ${verdict.tag} failed — the local tag was deleted again, nothing is cut (${(push.stderr || '').split('\n')[0]})`);
1515
1686
  }
1516
1687
  created = true;
1517
- published = publishPrerelease(repoAbs, { tag: verdict.tag, lastFinal, message });
1688
+ published = publishPrerelease(repoAbs, { tag: verdict.tag, lastFinal, message, final: !!verdict.final });
1518
1689
  }
1519
1690
  // #445: the `next` channel names the newest candidate — fast-forwarded in the run that pushed it.
1520
1691
  // Best-effort like the pre-release: the tag already stands, so a channel that cannot move is reported.
1692
+ // #446: a fast-route final moves `stable` instead — it is the newest final, and there is no candidate.
1521
1693
  const channel = verdict.ok && verdict.tag
1522
- ? releaseChannel.moveChannel(repoAbs, { remote, channel: releaseChannel.CHANNELS.next, sha, label: verdict.tag, dry: !!opts.dry })
1694
+ ? releaseChannel.moveChannel(repoAbs, { remote, channel: verdict.final ? releaseChannel.CHANNELS.stable : releaseChannel.CHANNELS.next, sha, label: verdict.tag, dry: !!opts.dry })
1523
1695
  : null;
1524
1696
 
1697
+ // #446: the fast route's own writes. A final: every issue it carries hears which version has it, and
1698
+ // an open tracking record for the version is closed. An ungranted migration: the hand-off is posted
1699
+ // on the version's tracking issue (opened if there is none), for a human to grant.
1700
+ let announced = null;
1701
+ let handoff = verdict.handoff || null;
1702
+ if (fast && !opts.dry) {
1703
+ if (created) {
1704
+ const exclude = (issues || []).filter((i) => releaseFinalize.parseReleaseMarker(i.body)).map((i) => i.number);
1705
+ announced = announceCarried(repoAbs, { tagNames: [...tags, verdict.tag], exclude, version: verdict.tag, sha });
1706
+ if (fastFacts.tracking) {
1707
+ commentOnce(repoAbs, fastFacts.tracking.number, { state: 'finalized', tag: verdict.tag }, `**${verdict.tag}** tagged final on \`${shortSha(sha)}\` by route deploy-tag-fast — the release workflow deploys it in this run.`);
1708
+ const r = tracker.forRepo(repoAbs).issueClose(fastFacts.tracking.number);
1709
+ if (!r.ok) warn(`could not close #${fastFacts.tracking.number}: ${String(r.stderr || '').split('\n')[0]}`);
1710
+ }
1711
+ } else if (handoff && verdict.version) {
1712
+ let num = fastFacts.tracking ? fastFacts.tracking.number : null;
1713
+ if (!num && issues !== null) {
1714
+ const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(verdict.version), body: releaseCut.handoffTrackingBody(verdict.version) });
1715
+ if (c.number) num = c.number;
1716
+ else warn(`could not open the tracking issue for ${verdict.version} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'}) — the hand-off is printed here only`);
1717
+ }
1718
+ if (num) {
1719
+ handoff = releaseCut.migrationHandoff(num, verdict.version);
1720
+ commentOnce(repoAbs, num, { state: 'migration-handoff', version: verdict.version },
1721
+ `**${verdict.version} carries a database migration**, and route deploy-tag-fast never deploys an ungranted one. The one command, run by a human, lets it ride — the next green run then tags and deploys it:\n\n\`\`\`sh\n${handoff}\n\`\`\``);
1722
+ }
1723
+ }
1724
+ }
1725
+
1525
1726
  if (opts.json) {
1526
1727
  print(JSON.stringify({
1527
1728
  repo: shortRepo(repoAbs), sha, ...(offTrunk ? { trunk } : {}), lastFinal, suggestion, dry: !!opts.dry, auto: !!opts.auto,
1528
- ok: verdict.ok, noop: !!verdict.noop, tag: verdict.tag, created, published, channel, version: verdict.version, bump: verdict.bump,
1729
+ ok: verdict.ok, noop: !!verdict.noop, standing: verdict.standing || [], tag: verdict.tag, created, published, channel, version: verdict.version, bump: verdict.bump,
1529
1730
  overridden: verdict.overridden, signals: verdict.signals ? verdict.signals.lines : null, checks: verdict.checks,
1731
+ // #446: present on every route, so the workflow reads one shape — final only on deploy-tag-fast.
1732
+ final: !!verdict.final,
1733
+ deploy: verdict.final && verdict.healthGate ? { healthUrl: verdict.healthGate.url, rollback: verdict.healthGate.rollback } : null,
1734
+ grant: verdict.grant || null, handoff, ...(fast ? { announced } : {}),
1530
1735
  }, null, 2));
1531
1736
  return verdict.ok || verdict.noop ? 0 : 1;
1532
1737
  }
@@ -1540,14 +1745,27 @@ function cmdReleaseCut(argv) {
1540
1745
  for (const c of verdict.checks) print(` ${c.ok ? '✓' : '✗'} ${c.condition.padEnd(width)} ${c.detail}`);
1541
1746
  print('');
1542
1747
  if (verdict.noop) {
1543
- print('· no-op — nothing owed, inside the route\'s cadence window, or main\'s head is not a promotion of trunk; nothing cut.');
1748
+ print(fast
1749
+ ? '· no-op — nothing owed, inside release.final-spacing, or main\'s head already carries a final; nothing tagged.'
1750
+ : '· no-op — nothing owed, inside the route\'s cadence window, or main\'s head is not a promotion of trunk; nothing cut.');
1544
1751
  return 0;
1545
1752
  }
1546
1753
  if (!verdict.ok) {
1547
1754
  print(`✗ refused — ${verdict.refusals.length} condition(s) failed; nothing cut.`);
1755
+ // #467: a refusal no further run clears by itself is a stall — say so, so nobody waits on it.
1756
+ if (verdict.standing && verdict.standing.length) print(` release stalled — ${verdict.standing.join(', ')} will not clear by itself; a human act is owed (the next run refuses the same way).`);
1757
+ if (handoff) print(`\nA migration rides this release. The one command, for a human to run:\n ${handoff}`);
1548
1758
  return 1;
1549
1759
  }
1550
- if (opts.dry) print(`[--dry] would create ${verdict.tag} on ${at}, push it to ${remote}, publish its GitHub pre-release and move the next channel. Nothing created.`);
1760
+ if (verdict.final) {
1761
+ 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.`);
1762
+ else {
1763
+ 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.`);
1764
+ if (published && published.ok) print(`✓ ${published.detail}`);
1765
+ else if (published) warn(`${published.detail} — the tag stands; publish it by hand: gh release create ${verdict.tag} --verify-tag --latest`);
1766
+ if (announced && announced.issues.length) print(`released in ${verdict.tag}: told ${announced.posted.length ? announced.posted.map((n) => `#${n}`).join(', ') : 'nobody new'}`);
1767
+ }
1768
+ } else if (opts.dry) print(`[--dry] would create ${verdict.tag} on ${at}, push it to ${remote}, publish its GitHub pre-release and move the next channel. Nothing created.`);
1551
1769
  else {
1552
1770
  print(`✓ cut ${verdict.tag} on ${at} and pushed it to ${remote} — a candidate, not a release; finalizing it is the release skill's.`);
1553
1771
  if (published && published.ok) print(`✓ ${published.detail}`);
@@ -1566,23 +1784,25 @@ function cmdReleaseCut(argv) {
1566
1784
  * workflow raced us) is left alone. Best-effort: the tag is already on origin, so a failure here is
1567
1785
  * reported, never a reason to undo the cut.
1568
1786
  */
1569
- function publishPrerelease(repoAbs, { tag, lastFinal, message }) {
1570
- if (!isGhUsable(repoAbs)) return { ok: false, detail: `pre-release NOT published: gh not usable (${ghUnusableWhy(repoAbs)})` };
1571
- const view = spawnSync('gh', ['release', 'view', tag, '--json', 'tagName'], { cwd: repoAbs, encoding: 'utf8' });
1572
- if (view.status === 0) return { ok: true, detail: `${tag} already has a GitHub Release — left as it is` };
1787
+ function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false }) {
1788
+ // #446: a deploy-tag-fast final is published as a full release, marked latest.
1789
+ const kind = final ? 'release' : 'pre-release';
1790
+ if (!isGhUsable(repoAbs)) return { ok: false, detail: `${kind} NOT published: gh not usable (${ghUnusableWhy(repoAbs)})` };
1791
+ const view = tracker.forRepo(repoAbs).releaseView(tag);
1792
+ if (view.ok) return { ok: true, detail: `${tag} already has a GitHub Release — left as it is` };
1573
1793
  let notes;
1574
1794
  try {
1575
1795
  notes = lastFinal ? buildReleaseNotes(repoAbs, `${lastFinal}..${tag}`, lastFinal).out : `## ${tag}\n\nFirst release.\n`;
1576
1796
  } catch (e) {
1577
1797
  notes = `## ${tag}\n\n(release notes unavailable: ${e.message})\n`;
1578
1798
  }
1579
- notes += `\n### Candidate record\n\n\`\`\`\n${message}\`\`\`\n`;
1799
+ notes += `\n### ${final ? 'Release' : 'Candidate'} record\n\n\`\`\`\n${message}\`\`\`\n`;
1580
1800
  const file = path.join(os.tmpdir(), `colab-release-notes-${process.pid}-${tag}.md`);
1581
1801
  fs.writeFileSync(file, notes);
1582
1802
  try {
1583
- const r = spawnSync('gh', releaseCut.prereleaseArgs(tag, file), { cwd: repoAbs, encoding: 'utf8' });
1584
- if (r.status !== 0) return { ok: false, detail: `pre-release NOT published: gh release create ${tag} failed (${(r.stderr || '').split('\n')[0] || r.status})` };
1585
- return { ok: true, detail: `published the GitHub pre-release ${tag}` };
1803
+ const r = tracker.forRepo(repoAbs).releaseCreate(tag, { notesFile: file, final });
1804
+ if (!r.ok) return { ok: false, detail: `${kind} NOT published: gh release create ${tag} failed (${(r.stderr || '').split('\n')[0] || r.code})` };
1805
+ return { ok: true, detail: `published the GitHub ${kind} ${tag}` };
1586
1806
  } finally {
1587
1807
  try { fs.unlinkSync(file); } catch (_) { /* best-effort */ }
1588
1808
  }
@@ -1659,8 +1879,8 @@ Conditions (--json checks[].condition; required:false means reported, not blocki
1659
1879
 
1660
1880
  manifest-version on-trunk outranks-final — #424's pre-tag checks, required before any final:
1661
1881
  the final equals every declared manifest version, its commit is on main (a shallow
1662
- checkout refuses), and it outranks the highest final tag. With release.version-source:
1663
- tag (#438) a manifest that differs is skipped as derivable and named, not refused
1882
+ checkout refuses), and it outranks the highest final tag. Under release.version-source:
1883
+ tag (#438; the default where the machine cuts the tag, #484) a manifest that differs is skipped as derivable and named, not refused
1664
1884
 
1665
1885
  final-grant migration-grant — #441, only where release.final-grant lets a deploy-tag final be
1666
1886
  automatic: the decision issue it names must still carry a recorded, trusted, not
@@ -1774,10 +1994,9 @@ function cmdReleaseFinalize(argv) {
1774
1994
  const t0 = version0 ? trackings.get(version0) : null;
1775
1995
  if (newest && t0 && !t0.error && !t0.number && !opts.dry) {
1776
1996
  const body = releaseFinalize.trackingBody({ version: version0, row: policy.derived.row, final: policy.effective.final, testPeriodDays: policy.effective.testPeriodDays });
1777
- const c = spawnSync('gh', ['issue', 'create', '--title', releaseFinalize.trackingTitle(version0), '--body', body], { cwd: repoAbs, encoding: 'utf8' });
1778
- const m = c.status === 0 ? /\/issues\/([0-9]+)/.exec(c.stdout || '') : null;
1779
- if (!m) trackings.set(version0, { error: `could not open the tracking issue for ${version0} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'})` });
1780
- else { trackings.set(version0, { number: Number(m[1]), url: (c.stdout || '').trim(), createdAt: now, held: false }); trackingCreated = true; }
1997
+ const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(version0), body });
1998
+ 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'})` });
1999
+ else { trackings.set(version0, { number: c.number, url: c.url, createdAt: now, held: false }); trackingCreated = true; }
1781
2000
  }
1782
2001
 
1783
2002
  // #441: an operator-granted automatic final — the decision it names is resolved once per run, from
@@ -1829,7 +2048,7 @@ function cmdReleaseFinalize(argv) {
1829
2048
  manifests, ancestry, tags: tagNames, finalGrant, migrations,
1830
2049
  human: { bar: humanBar, answeredBy: opts.answeredBy || null },
1831
2050
  });
1832
- return { candidate: cand, verdict, period, tracking };
2051
+ return { candidate: cand, verdict, period, tracking, trunk };
1833
2052
  };
1834
2053
 
1835
2054
  let cand = null; let verdict; let period = null; let tracking = version0 ? trackings.get(version0) : null;
@@ -1837,14 +2056,23 @@ function cmdReleaseFinalize(argv) {
1837
2056
  if (walk) {
1838
2057
  const MAX_JUDGED = 10;
1839
2058
  const evals = [];
2059
+ // #468: every red trunk run a judged candidate's window held. One red run puts every candidate cut
2060
+ // in the test period before it into needs-new-candidate; on a repo cutting several a day, judging
2061
+ // each one in full spent MAX_JUDGED on them and the walk stopped before the older clean one.
2062
+ const knownRed = [];
1840
2063
  for (const c of releaseFinalize.openCandidates(tags, remote)) {
1841
- if (c.refused) { skipped.push({ tag: c.tag, state: 'refused', detail: c.refused }); continue; }
2064
+ if (c.refused) { skipped.push({ tag: c.tag, state: 'refused', detail: c.refused, endsAt: null }); continue; }
1842
2065
  const tr = trackings.has(c.version) ? trackings.get(c.version) : trackingFor(c.version, { isCandidate: true });
1843
2066
  const p = releaseFinalize.periodVerdict({ cutAt: c.cutAt, trackingCreatedAt: tr && tr.createdAt, testPeriodDays: policy.effective.testPeriodDays, now });
1844
2067
  // Cheap skip: a younger candidate whose own period has not elapsed cannot finalize — only the newest is judged regardless, so the report has a state.
1845
- if (!p.elapsed && evals.length) { skipped.push({ tag: c.tag, state: 'testing', detail: p.detail }); continue; }
2068
+ if (!p.elapsed && evals.length) { skipped.push({ tag: c.tag, state: 'testing', detail: `test-period: ${p.detail}`, endsAt: p.endsAt }); continue; }
2069
+ // #468: cheap skip, the second kind — a red run already seen inside this candidate's own window.
2070
+ // Not counted toward MAX_JUDGED. May be wrong only in the safe direction (windowHasRed).
2071
+ const seenRed = evals.length ? releaseFinalize.windowHasRed(p, knownRed) : null;
2072
+ if (seenRed) { skipped.push({ tag: c.tag, state: 'needs-new-candidate', detail: `trunk-green: trunk went red at ${seenRed}, inside its own test period (seen judging a newer candidate)`, endsAt: p.endsAt }); continue; }
1846
2073
  const e = judge(c, { kind: 'candidate', candidate: c, superseded: [], detail: `${c.tag} at ${shortSha(c.sha)}, cut ${c.cutAt} (--auto: judged on its own clock)` });
1847
2074
  evals.push(e);
2075
+ if (e.trunk && Array.isArray(e.trunk.redAt)) knownRed.push(...e.trunk.redAt);
1848
2076
  if (e.verdict.state === 'finalized' || e.verdict.state === 'held' || evals.length >= MAX_JUDGED) break;
1849
2077
  }
1850
2078
  const pick = releaseFinalize.pickNewestClean(evals);
@@ -1871,28 +2099,13 @@ function cmdReleaseFinalize(argv) {
1871
2099
  if (!r.ok) warn(`could not comment on #${num}: ${String(r.stderr || '').split('\n')[0]}`);
1872
2100
  };
1873
2101
  const close = (num) => {
1874
- const r = spawnSync('gh', ['issue', 'close', String(num)], { cwd: repoAbs, encoding: 'utf8' });
1875
- if (r.status !== 0) warn(`could not close #${num}: ${String(r.stderr || '').split('\n')[0]}`);
2102
+ const r = tracker.forRepo(repoAbs).issueClose(num);
2103
+ if (!r.ok) warn(`could not close #${num}: ${String(r.stderr || '').split('\n')[0]}`);
1876
2104
  };
1877
2105
  // #426: one "Released in vX.Y.Z" comment on every issue the version carries (release-finalize.js
1878
2106
  // carriedIssues — the closing references in (previous final, sha]). Idempotent by event marker.
1879
2107
  let announced = null;
1880
- const announceRelease = (version, sha) => {
1881
- const prev = releaseFinalize.previousFinal(tagNames, version);
1882
- if (!prev) return { range: null, issues: [], posted: [], skipped: [], detail: 'no previous final — the first version announces nothing' };
1883
- const log = git.git(['log', '--format=%B%x00', `${prev}..${sha}`], repoAbs);
1884
- if (!log.ok) { warn(`could not read ${prev}..${shortSha(sha)} — no issue told it was released in ${version}`); return { range: `${prev}..${version}`, issues: [], posted: [], skipped: [], detail: 'git log failed' }; }
1885
- const nums = releaseFinalize.carriedIssues(log.stdout.split('\0'), { exclude: records.map((r) => r.number) });
1886
- const posted = []; const skipped = [];
1887
- for (const n of nums) {
1888
- const view = git.ghIssueView(repoAbs, n, ['comments']);
1889
- if (!view) { skipped.push(n); continue; }
1890
- if (releaseFinalize.hasEvent(view.comments, releaseFinalize.releasedEvent(version))) continue;
1891
- const r = git.ghIssueComment(repoAbs, n, releaseFinalize.releasedComment(version, sha));
1892
- if (r.ok) posted.push(n); else { skipped.push(n); warn(`could not comment on #${n}: ${String(r.stderr || '').split('\n')[0]}`); }
1893
- }
1894
- return { range: `${prev}..${version}`, issues: nums, posted, skipped };
1895
- };
2108
+ const announceRelease = (version, sha) => announceCarried(repoAbs, { tagNames, exclude: records.map((r) => r.number), version, sha });
1896
2109
  if (!opts.dry) {
1897
2110
  if (verdict.state === 'finalized') {
1898
2111
  const actor = humanBar && !verdict.grant ? `${opts.answeredBy} (human bar: COLAB_HUMAN=1)` : `automatic — clean test period (CONVENTIONS.md §6)${verdict.grant ? `, by the operator's grant (decision #${verdict.grant.issue})` : ''}${walk ? ', newest candidate clean on its own clock (--auto)' : ''}`;
@@ -1956,13 +2169,16 @@ function cmdReleaseFinalize(argv) {
1956
2169
  const trackingOut = tracking && !tracking.error
1957
2170
  ? { number: tracking.number || null, url: tracking.url || null, created: trackingCreated && (!cand || cand.version === version0), held: !!tracking.held, supersededHeld }
1958
2171
  : null;
2172
+ // #468: why this run made no final, and which candidate finals first — the line the release
2173
+ // workflow prints, so "no final" never has to be reconstructed from a checklist.
2174
+ const why = releaseFinalize.whyNoFinal({ state: verdict.state, candidate: cand, checks: verdict.checks, period, skipped: walk ? skipped : [], now });
1959
2175
  if (opts.json) {
1960
2176
  print(JSON.stringify({
1961
2177
  repo: shortRepo(repoAbs), row: policy.derived.row, route: policy.effective.route, final: policy.effective.final, testPeriodDays: policy.effective.testPeriodDays,
1962
2178
  lastFinal, dry: !!opts.dry, auto: !!opts.auto, candidate: cand, tracking: trackingOut,
1963
2179
  periodStart: period ? period.start : null, periodEndsAt: period ? period.endsAt : null,
1964
2180
  state: verdict.state, tagged, finalTag: verdict.finalTag, checks: verdict.checks, handoff: verdict.handoff,
1965
- skipped: walk ? skipped : undefined, announced, grant: verdict.grant || null, channel,
2181
+ skipped: walk ? skipped : undefined, why, next: why ? why.next : null, announced, grant: verdict.grant || null, channel,
1966
2182
  }, null, 2));
1967
2183
  } else {
1968
2184
  print(`colab release finalize${opts.auto ? ' --auto' : ''} — ${shortRepo(repoAbs)} (last final: ${lastFinal || 'none'}${cand ? `, candidate: ${cand.tag}` : ''})`);
@@ -1974,6 +2190,7 @@ function cmdReleaseFinalize(argv) {
1974
2190
  }
1975
2191
  print('');
1976
2192
  print(`state: ${verdict.state}${opts.dry ? ' [--dry: nothing written]' : ''}${tagged ? ` — tagged ${verdict.finalTag} and pushed it to ${remote}` : ''}`);
2193
+ if (why) print(`why no final: ${why.line}`);
1977
2194
  if (announced && announced.issues.length) print(`released in ${verdict.finalTag || version0}: told ${announced.posted.length ? announced.posted.map((n) => `#${n}`).join(', ') : 'nobody new'} (carried: ${announced.issues.map((n) => `#${n}`).join(', ')}${announced.skipped.length ? `; unreadable: ${announced.skipped.map((n) => `#${n}`).join(', ')}` : ''})`);
1978
2195
  if (channel && channel.ok) print(`✓ ${channel.detail}`);
1979
2196
  else if (channel) warn(`${channel.detail} — the final tag stands`);
@@ -2039,7 +2256,7 @@ function cmdRelease(argv) {
2039
2256
  });
2040
2257
  if (opts.help || opts._.length === 0) return print(HELP_RELEASE);
2041
2258
  const num = normIssueNum(opts._[0]);
2042
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
2259
+ const repoAbs = resolveRepoOrCwd(opts);
2043
2260
 
2044
2261
  // #164: look the claim up WITHOUT deleting it yet — the gh write below can fail (GraphQL AND
2045
2262
  // REST both rate-limited, network down, ...), and deleting first would clear the one local
@@ -2065,7 +2282,7 @@ function cmdRelease(argv) {
2065
2282
  * Returns { ghFailed, worktree, remaining }.
2066
2283
  */
2067
2284
  function releaseFoundClaim(num, found, opts = {}) {
2068
- const repo = found.claim.repo;
2285
+ const repo = found.repo || found.claim.repo; // #487: the MAIN root, even for a legacy worktree-keyed row
2069
2286
  const wtName = found.claim.worktree;
2070
2287
 
2071
2288
  let ghFailed = false;
@@ -2188,7 +2405,7 @@ function cmdIssueFiled(argv) {
2188
2405
  });
2189
2406
  if (opts.help || opts._.length === 0) return print(HELP_ISSUE_FILED);
2190
2407
  const num = normIssueNum(opts._[0]);
2191
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
2408
+ const repoAbs = resolveRepoOrCwd(opts);
2192
2409
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
2193
2410
 
2194
2411
  pushEvent('issue-filed', { repo: repoAbs, issue: num });
@@ -2283,7 +2500,7 @@ function cmdClose(argv) {
2283
2500
  if (already) {
2284
2501
  print(` #${num} is already closed — skipping the close; releasing and notifying anyway`);
2285
2502
  } else {
2286
- const r = git.run('gh', ['issue', 'close', String(num), '--reason', ghReason], { cwd: repoAbs });
2503
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: ghReason });
2287
2504
  if (!r.ok) {
2288
2505
  process.stderr.write(`✗ gh issue close #${num} failed (${(r.stderr || '').split('\n')[0] || r.code}) — claim untouched.\n`);
2289
2506
  return 1;
@@ -2360,7 +2577,7 @@ function cmdGateRecorded(argv) {
2360
2577
  });
2361
2578
  if (opts.help) return print(HELP_GATE_RECORDED);
2362
2579
 
2363
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.mainRepoRoot(process.cwd()) || null);
2580
+ const repoAbs = resolveRepoOrCwd(opts);
2364
2581
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
2365
2582
 
2366
2583
  let wtName = opts.worktree || null;
@@ -3134,7 +3351,7 @@ function cmdReadiness(argv) {
3134
3351
  });
3135
3352
  if (opts.help || opts._.length === 0) return print(HELP_READINESS);
3136
3353
  const num = normIssueNum(opts._[0]);
3137
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
3354
+ const repoAbs = resolveRepoOrCwd(opts);
3138
3355
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3139
3356
 
3140
3357
  // No local fallback, on purpose. A claim can degrade to local-only because it also has a fast
@@ -3334,7 +3551,7 @@ function cmdBlocked(argv) {
3334
3551
  });
3335
3552
  if (argErr) throw new UserError(argErr);
3336
3553
 
3337
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
3554
+ const repoAbs = resolveRepoOrCwd(opts);
3338
3555
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3339
3556
 
3340
3557
  if (!isGhUsable(repoAbs)) {
@@ -3531,17 +3748,28 @@ ROLE-TAGGED GRANTS (#397). --role defaults to \`human\` — the grant above, unc
3531
3748
  --role ${migrationGrant.REVIEWER_ROLE} the comment is a \`${migrationGrant.REVIEW_GRANT_MARK}\` instead:
3532
3749
  it names the declared reviewer and carries a REVIEW RECORD (a \`\`\`${migrationGrant.REVIEW_RECORD_FENCE}
3533
3750
  block — verdict, checklist result, the escalation condition checked, the CI round-trip result, and
3534
- the reviewed HEAD sha). A reviewer grant is bound to that HEAD: any new commit on the branch voids it.
3751
+ the reviewed HEAD sha, and — #508 — \`migrations\`, a content id over the branch's migration files at
3752
+ that HEAD, computed here, never a flag). A reviewer grant is bound to that CONTENT: a commit that
3753
+ leaves every migration file byte-identical (the trunk sync ship requires) keeps it; editing, adding,
3754
+ removing or renaming a migration voids it. A branch with no migration file gets no id and is bound to
3755
+ its HEAD alone, as is every record minted before #508.
3535
3756
  It is minted only when ALL of these hold, checked before any network call:
3536
3757
  - the record is well-formed AND passing (approve · checklist pass · escalation clear · CI pass) —
3537
3758
  a grant carrying a failing review is a contradiction, so it is refused, not recorded;
3538
3759
  - the branch is pushed, and --head (if given) equals origin's tip — the grant binds that tip;
3539
- - this checkout's project.yml declares \`migration-grant: reviewer\` (#398; absent = human).
3760
+ - this checkout's project.yml declares \`migration-grant: reviewer\` (#398; absent = human);
3761
+ - checklist-items, when given, is <passed>/${migrationGrant.REVIEW_CHECKLIST_ITEMS} and, with checklist pass, every item
3762
+ passed (#457) — the record counts against the checklist the migration-review skill walks today.
3763
+ Then, read from CI after the tracker read and before anything is written (#457):
3764
+ - ci-roundtrip pass is TRUE at the head: the "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" job ran and
3765
+ passed there (the rule ship applies), and --ci-run, when given, is one of the runs at that
3766
+ head and carries the job. A repo whose CI has no such job cannot mint a reviewer grant at all.
3540
3767
  COLAB_HUMAN=1 is still required for every role. The reviewer identity is DECLARED, not attested.
3541
3768
  \`colab ship\` honours a reviewer grant only when ALL of (#401): P the target's project.yml says
3542
3769
  \`migration-grant: reviewer\` · M this record is live, trusted and passing · HEAD its head is the
3543
- branch's exact remote head · R the live "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job passed on that
3544
- HEAD (re-read by ship, never taken from the record). Any condition failing → a human runs Phase B.
3770
+ branch's exact remote head, or its \`migrations\` id equals the id at that head · R the live
3771
+ "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job passed on the SHIPPED head (re-read by ship, never
3772
+ taken from the record). Any condition failing → a human runs Phase B.
3545
3773
 
3546
3774
  Options:
3547
3775
  --branch <branch> required for --branch grants; a grant is never inferred from HEAD
@@ -3589,7 +3817,7 @@ function cmdMigrationGrant(argv) {
3589
3817
  return 1;
3590
3818
  }
3591
3819
 
3592
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
3820
+ const repoAbs = resolveRepoOrCwd(opts);
3593
3821
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3594
3822
 
3595
3823
  // Argument validation and local ref resolution run BEFORE isGhUsable, deliberately — they are
@@ -3660,11 +3888,22 @@ function migrationGrantReviewRecord(repoAbs, opts) {
3660
3888
  throw new UserError(`--head ${String(opts.head).slice(0, 12)} is not origin's tip of "${opts.branch}" (${tip.slice(0, 12)}) — the review covers a commit the grant would not bind; re-review the tip`);
3661
3889
  }
3662
3890
 
3891
+ // #508: bind what was reviewed — the branch's migration files at the tip, by content. Same path
3892
+ // rule the ship gate fires on (newMigrations), against origin's trunk. A branch with no migration
3893
+ // to review gets no id and stays HEAD-bound.
3894
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
3895
+ const remote = git.remoteInfo(repoAbs).name || 'origin';
3896
+ let base = trunk ? `${remote}/${trunk}` : null;
3897
+ if (base && !git.git(['rev-parse', '--verify', '--quiet', `${base}^{commit}`], repoAbs).ok) base = trunk;
3898
+ const migrations = base ? newMigrations(repoAbs, base, tip) : [];
3899
+ const contentId = migrationContentAt(repoAbs, migrations, tip);
3900
+
3663
3901
  const rec = {
3664
3902
  v: '1', role, reviewer: opts.reviewer, head: tip,
3665
3903
  verdict: opts.verdict, checklist: opts.checklist, 'checklist-items': opts.checklistItems,
3666
3904
  escalation: opts.escalation, 'escalation-result': opts.escalationResult,
3667
3905
  'ci-roundtrip': opts.ciRoundtrip, 'ci-run': opts.ciRun,
3906
+ migrations: contentId || undefined,
3668
3907
  };
3669
3908
  for (const k of Object.keys(rec)) if (rec[k] === undefined) delete rec[k];
3670
3909
  const v = migrationGrant.validateReviewRecord(rec);
@@ -3672,9 +3911,36 @@ function migrationGrantReviewRecord(repoAbs, opts) {
3672
3911
  if (!v.passing) {
3673
3912
  throw new UserError(`the review does not pass (${migrationGrant.reviewRecordFailure(rec)}) — a grant carrying a failing review is a contradiction; nothing was posted`);
3674
3913
  }
3914
+ // #457: checks only a NEW record faces (the checklist denominator) — local, so before the gh gate.
3915
+ const mintProblems = migrationGrant.mintRecordProblems(rec);
3916
+ if (mintProblems.length) throw new UserError(`the review record is invalid: ${mintProblems.join('; ')}`);
3675
3917
  return rec;
3676
3918
  }
3677
3919
 
3920
+ /**
3921
+ * #457: the record says `ci-roundtrip: pass` — read CI at its head and refuse unless the round-trip
3922
+ * job is really there and passed (tools/lib/migration-grant.js mintRoundtripCheck: the same
3923
+ * roundtripVerdict `colab ship` applies, plus the cited `ci-run` must carry the job). Needs gh, so
3924
+ * it runs in cmdMigrationGrantCreate after the tracker read and BEFORE the label is applied —
3925
+ * nothing is written when it refuses. The workflows guard diffs trunk against the reviewed head;
3926
+ * an unreadable diff counts as touched, failing closed exactly as shipMigrationCtx does.
3927
+ */
3928
+ function migrationGrantRoundtripCheck(repoAbs, branch, rec) {
3929
+ if (rec['ci-roundtrip'] !== 'pass') return;
3930
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
3931
+ const remote = git.remoteInfo(repoAbs).name || 'origin';
3932
+ let d = trunk ? git.git(['diff', '--name-only', `${remote}/${trunk}...${rec.head}`], repoAbs) : { ok: false };
3933
+ if (!d.ok && trunk) d = git.git(['diff', '--name-only', `${trunk}...${rec.head}`], repoAbs);
3934
+ const workflowsTouched = !d.ok || d.stdout.split('\n').some((f) => f.startsWith('.github/workflows/'));
3935
+ let runs = null;
3936
+ const list = git.ghRunsForCommit(repoAbs, branch, rec.head, 20);
3937
+ if (Array.isArray(list)) {
3938
+ runs = list.map((r) => ({ databaseId: r.databaseId, workflowName: r.workflowName || null, jobs: git.ghRunJobs(repoAbs, r.databaseId) }));
3939
+ }
3940
+ const c = migrationGrant.mintRoundtripCheck(rec, runs, { workflowsTouched });
3941
+ if (!c.ok) throw new UserError(`${c.reason}; nothing was posted`);
3942
+ }
3943
+
3678
3944
  function cmdMigrationGrantCreate(repoAbs, num, opts) {
3679
3945
  // --branch and branch existence are already validated by cmdMigrationGrant, ahead of the
3680
3946
  // isGhUsable gate — see the comment there. Kept as a defensive re-check in case this function is
@@ -3698,6 +3964,9 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
3698
3964
  || `this repo has no \`${labels.MIGRATION_GRANT_LABEL}\` label`);
3699
3965
  }
3700
3966
 
3967
+ // #457: a record claiming a CI round-trip pass is checked against CI BEFORE anything is written.
3968
+ if (opts.reviewRecord) migrationGrantRoundtripCheck(repoAbs, opts.branch, opts.reviewRecord);
3969
+
3701
3970
  const editR = git.ghIssueEdit(repoAbs, num, labels.migrationGrantLabelArgs({}));
3702
3971
  if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
3703
3972
 
@@ -3717,7 +3986,11 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
3717
3986
 
3718
3987
  if (opts.reviewRecord) {
3719
3988
  print(`Recorded a ${migrationGrant.REVIEWER_ROLE} grant on #${num} in ${shortRepo(repoAbs)} — reviewer "${opts.reviewRecord.reviewer}", branch "${opts.branch}" @ ${opts.reviewRecord.head.slice(0, 12)}.`);
3720
- print(' Bound to that HEAD: any new commit voids it. It expires the moment the issue closes.');
3989
+ if (opts.reviewRecord.migrations) {
3990
+ print(` Bound to the reviewed migration content ${opts.reviewRecord.migrations.slice(0, 12)}: a commit that leaves every migration file byte-identical (a trunk sync) keeps it, any change to one voids it. It expires the moment the issue closes.`);
3991
+ } else {
3992
+ print(' Bound to that HEAD: any new commit voids it. It expires the moment the issue closes.');
3993
+ }
3721
3994
  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.`);
3722
3995
  print(` Revoke any time: colab migration-grant ${num} --revoke`);
3723
3996
  return 0;
@@ -3765,7 +4038,7 @@ function cmdMigrationGrantRevoke(repoAbs, num) {
3765
4038
  }
3766
4039
 
3767
4040
  function cmdMigrationGrantList(opts) {
3768
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4041
+ const repoAbs = resolveRepoOrCwd(opts);
3769
4042
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3770
4043
  if (!isGhUsable(repoAbs)) {
3771
4044
  throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — cannot list migration grants`);
@@ -3900,7 +4173,7 @@ function cmdDecision(argv) {
3900
4173
  throw new UserError('--ruled-by <name> is required — names the human whose call this is, never the typist (CONVENTIONS.md §5, Provenance)');
3901
4174
  }
3902
4175
 
3903
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4176
+ const repoAbs = resolveRepoOrCwd(opts);
3904
4177
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3905
4178
 
3906
4179
  if (!isGhUsable(repoAbs)) {
@@ -4046,7 +4319,7 @@ function cmdDecisionReopen(repoAbs, num, opts, body) {
4046
4319
  }
4047
4320
 
4048
4321
  function cmdDecisionList(opts) {
4049
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4322
+ const repoAbs = resolveRepoOrCwd(opts);
4050
4323
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4051
4324
  if (!isGhUsable(repoAbs)) {
4052
4325
  throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — cannot list decisions`);
@@ -4128,6 +4401,7 @@ function cmdDecisionList(opts) {
4128
4401
  // ---------------------------------------------------------------------------
4129
4402
 
4130
4403
  const HELP_CI_GRANT = `colab ci-grant <issue> --branch <branch> [--evidence-run <sha-or-url>] [--repo <path>]
4404
+ colab ci-grant <issue> --branch <branch> --role ci-reviewer --reviewer <id> --verdict pass --cures <checks> [--repo <path>]
4131
4405
  colab ci-grant <issue> --revoke [--repo <path>]
4132
4406
  colab ci-grant --list [--json] [--repo <path>]
4133
4407
 
@@ -4166,8 +4440,9 @@ CI grant merges into a repo whose own test suite is known-failing:
4166
4440
  \`ship\` would never consult it for, reading live in \`--list\` while doing nothing.
4167
4441
 
4168
4442
  HUMAN-ONLY, ENFORCED: both grant and revoke REFUSE (exit 1) unless COLAB_HUMAN=1 is set in the
4169
- environment — the identical bar \`colab promote\`/\`colab migration-grant\` already hold. No field,
4170
- flag or project.yml value can lower it. This check runs BEFORE any network call.
4443
+ environment — the identical bar \`colab promote\`/\`colab migration-grant\` already hold. This check
4444
+ runs BEFORE any network call. The ONE exception is the reviewer role below, and only on a repo whose
4445
+ trunk opts in.
4171
4446
 
4172
4447
  The marker is TWO parts, both required for a grant to read as live:
4173
4448
  - the \`${labels.CI_GRANT_LABEL}\` label — applying it requires GitHub write/triage permission, so
@@ -4195,8 +4470,30 @@ Revoking removes the label FIRST (the gate is restored the same minute) and post
4195
4470
  There is deliberately no local-only fallback: without a usable \`gh\`, every subcommand here REFUSES
4196
4471
  rather than write (or read) something invisible to the machine \`ship\` might later run on.
4197
4472
 
4473
+ THE REVIEWER ROLE (#504). On a repo whose TRUNK declares \`ci-grant: reviewer\` in project.yml,
4474
+ --role ${ciGrant.REVIEWER_ROLE} mints a \`${ciGrant.REVIEW_GRANT_MARK}\` WITHOUT COLAB_HUMAN=1 — the coordinator
4475
+ agent's door through a red trunk the cure rule refuses (maintainer ruling 2026-10-05). It is the only
4476
+ path past the human bar above, and only that opt-in opens it; revoking stays human. Every guard is
4477
+ measured, nothing is taken from the flags:
4478
+ - local, before any network call: the opt-in on trunk as committed (a branch cannot opt itself
4479
+ in) · the record is well-formed with --verdict pass and at least one cure · the branch is
4480
+ pushed and --head (if given) is origin's tip · the branch's trailing number group carries #N;
4481
+ - #N is open and its title starts "${ciGrant.TRUNK_RED_TITLE_PREFIX}" · trunk is red in ship's sense ·
4482
+ never stacks (guard 2 above) · the branch's own CI is green at that EXACT head · every
4483
+ check in --cures is red on trunk at the red sha.
4484
+ The comment carries a fenced \`ci-review\` record (verdict, head, red sha, cures) and binds that
4485
+ HEAD and that red sha: a new commit on either voids it. \`colab ship\` re-measures all of it, reads
4486
+ the opt-in at the merge target, and reads a grant with \`not-before\` in the future as not yet usable.
4487
+
4198
4488
  Options:
4199
4489
  --branch <branch> required for a grant; never inferred from HEAD
4490
+ --role <role> human (default) | ${ciGrant.REVIEWER_ROLE}
4491
+ --reviewer <id> (reviewer) the reviewer's declared identity (letters, digits, . _ @ -)
4492
+ --verdict <v> (reviewer) pass | fail — only pass is minted
4493
+ --cures <checks> (reviewer) the red checks the branch cures, "workflow / job; …"
4494
+ --head <sha> (reviewer) optional; must equal the pushed branch tip
4495
+ --not-before <iso> (reviewer) optional; a revoke window the host imposes
4496
+ --ci-run <id-or-url> (reviewer) optional; recorded only
4200
4497
  --evidence-run <ref> recording-only note for the audit trail — never substitutes for the
4201
4498
  measured branch-head run this command itself checks
4202
4499
  --revoke revoke instead of grant
@@ -4225,7 +4522,10 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4225
4522
  let priorGrantMerge = null;
4226
4523
  if (priorLog.ok && priorLog.stdout.trim()) {
4227
4524
  const [sha, at] = priorLog.stdout.trim().split('\n')[0].split('\t');
4228
- priorGrantMerge = { sha, at };
4525
+ // #477: the red sha that exemption was measured against, off its own trailer — what the cure
4526
+ // rule's progress admission compares today's red set with. null when unreadable (refuses there).
4527
+ const body = git.git(['log', '-1', '--format=%B', sha], repoAbs);
4528
+ priorGrantMerge = { sha, at, redSha: body.ok ? ciCure.priorRedShaFromMessage(body.stdout) : null };
4229
4529
  }
4230
4530
  let redContinuousSincePriorGrant = false;
4231
4531
  if (priorGrantMerge) {
@@ -4237,11 +4537,10 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4237
4537
  // local offset is positive (tools/lib/ci-grant.js's wentGreenSince doc comment has the full
4238
4538
  // failure).
4239
4539
  let wentGreen = false;
4240
- const runsR = git.run('gh', ['run', 'list', '--branch', trunk, '-L', '100',
4241
- '--json', 'conclusion,status,createdAt'], { cwd: repoAbs });
4242
- if (runsR.ok) {
4540
+ const runsR = tracker.forRepo(repoAbs).runList({ branch: trunk, limit: 100, fields: ['conclusion', 'status', 'createdAt'] });
4541
+ if (runsR.data) {
4243
4542
  try {
4244
- wentGreen = ciGrant.wentGreenSince(JSON.parse(runsR.stdout), priorGrantMerge.at);
4543
+ wentGreen = ciGrant.wentGreenSince(runsR.data, priorGrantMerge.at);
4245
4544
  } catch (_) { /* unparseable — treat conservatively as "cannot prove it went green" */ }
4246
4545
  }
4247
4546
  redContinuousSincePriorGrant = !wentGreen;
@@ -4251,7 +4550,12 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4251
4550
 
4252
4551
  function cmdCiGrant(argv) {
4253
4552
  const opts = parseArgs(argv, {
4254
- values: { '--repo': 'repo', '--branch': 'branch', '--evidence-run': 'evidenceRun' },
4553
+ values: {
4554
+ '--repo': 'repo', '--branch': 'branch', '--evidence-run': 'evidenceRun',
4555
+ // #504 reviewer-grant record flags
4556
+ '--role': 'role', '--reviewer': 'reviewer', '--verdict': 'verdict', '--cures': 'cures',
4557
+ '--head': 'head', '--not-before': 'notBefore', '--ci-run': 'ciRun',
4558
+ },
4255
4559
  flags: { '--revoke': 'revoke', '--list': 'list', '--json': 'json', '-h': 'help', '--help': 'help' },
4256
4560
  });
4257
4561
  if (opts.help) return print(HELP_CI_GRANT);
@@ -4259,15 +4563,31 @@ function cmdCiGrant(argv) {
4259
4563
  if (opts._.length === 0) return print(HELP_CI_GRANT);
4260
4564
  const num = normIssueNum(opts._[0]);
4261
4565
 
4566
+ // #504: the reviewer role is the ONE path past the human bar below, and only on a repo whose
4567
+ // TRUNK declares `ci-grant: reviewer`. Decided from local git alone, before any network call.
4568
+ const role = opts.role === undefined ? 'human' : String(opts.role);
4569
+ if (!ciGrant.GRANT_ROLES.includes(role)) {
4570
+ throw new UserError(`--role is "${role}", expected ${ciGrant.GRANT_ROLES.join(' | ')}`);
4571
+ }
4572
+ if (opts.revoke && opts.role !== undefined) {
4573
+ throw new UserError('--revoke takes no --role — a revoke cancels every live grant on the issue, whatever its role');
4574
+ }
4575
+ if (role === ciGrant.REVIEWER_ROLE && !opts.revoke) return cmdCiGrantReviewer(num, opts);
4576
+ const stray = ['reviewer', 'verdict', 'cures', 'head', 'notBefore', 'ciRun'].filter((k) => opts[k] !== undefined);
4577
+ if (stray.length) {
4578
+ throw new UserError(`review-record flags (${stray.map((k) => '--' + k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase())).join(', ')}) need --role ${ciGrant.REVIEWER_ROLE} — a human grant carries no record`);
4579
+ }
4580
+
4262
4581
  // HUMAN-ONLY, first — identical posture and identical reason to cmdMigrationGrant's check above:
4263
4582
  // assertable by a test against a fixture with no `gh` at all (tools/lib/ship-ci-grant.test.js).
4264
4583
  if (process.env.COLAB_HUMAN !== '1') {
4265
4584
  process.stderr.write(`✗ Refusing: ${opts.revoke ? 'revoking' : 'creating'} a CI grant requires a human.\n`);
4266
4585
  process.stderr.write(' Re-run with COLAB_HUMAN=1. (No field, flag or project.yml value can lower this bar.)\n');
4586
+ if (!opts.revoke) process.stderr.write(` The ${ciGrant.REVIEWER_ROLE} role is a different grant, open only where trunk declares ci-grant: reviewer — colab ci-grant --help.\n`);
4267
4587
  return 1;
4268
4588
  }
4269
4589
 
4270
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4590
+ const repoAbs = resolveRepoOrCwd(opts);
4271
4591
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4272
4592
 
4273
4593
  // Argument validation and local ref resolution BEFORE isGhUsable — same reasoning as
@@ -4287,6 +4607,121 @@ function cmdCiGrant(argv) {
4287
4607
  return opts.revoke ? cmdCiGrantRevoke(repoAbs, num) : cmdCiGrantCreate(repoAbs, num, opts);
4288
4608
  }
4289
4609
 
4610
+ /**
4611
+ * #504: `colab ci-grant <N> --role ci-reviewer` — the coordinator agent's door through a red trunk the
4612
+ * cure rule refuses. Needs no COLAB_HUMAN=1, and that is the whole point; what replaces the human is
4613
+ * the opt-in on trunk plus guards that are all MEASURED here, never taken from the flags:
4614
+ * local (before any network call): `ci-grant: reviewer` committed on trunk · the record is
4615
+ * well-formed with verdict pass and at least one cure · the branch is pushed and --head (if
4616
+ * given) is its remote tip · the branch name's trailing number group carries #N;
4617
+ * tracker/CI: #N is open and titled `TRUNK RED:` · trunk is red in the sense ship checks · never
4618
+ * stacks (computeAntiStacking, same as the human grant) · the branch's own CI is green at that
4619
+ * EXACT head · every claimed cure is a red check on trunk at the red sha.
4620
+ * Nothing is written until all of them pass.
4621
+ */
4622
+ function cmdCiGrantReviewer(num, opts) {
4623
+ const repoAbs = resolveRepoOrCwd(opts);
4624
+ if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4625
+ if (!opts.branch) {
4626
+ throw new UserError('--branch <branch> is required — a grant is bound to one branch, never inferred from the current checkout');
4627
+ }
4628
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
4629
+ if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
4630
+
4631
+ // The opt-in, read from TRUNK as committed — never this checkout or the branch, so a branch cannot
4632
+ // grant itself the policy it would then use.
4633
+ const pol = ciGrant.parseGrantPolicy(projectDocAt(repoAbs, trunk));
4634
+ if (!pol.valid) throw new UserError(`${pol.reason} — fix project.yml on ${trunk} before minting a reviewer grant`);
4635
+ if (pol.policy !== 'reviewer') {
4636
+ process.stderr.write(`✗ Refusing: ${trunk}'s project.yml says ci-grant: ${pol.policy}${pol.declared ? '' : ' (absent = human)'} — a ${ciGrant.REVIEWER_ROLE} grant is minted only where trunk declares ci-grant: reviewer.\n`);
4637
+ process.stderr.write(' Without that opt-in a CI grant is human-only: COLAB_HUMAN=1 colab ci-grant <N> --branch <b>.\n');
4638
+ return 1;
4639
+ }
4640
+
4641
+ if (!branchName.branchIssueNumbers(opts.branch).includes(num)) {
4642
+ throw new UserError(`branch "${opts.branch}" does not carry #${num} in its trailing number group — a reviewer grant needs the branch to close the TRUNK RED issue it is posted on`);
4643
+ }
4644
+ const refs = git.branchRefs(repoAbs, opts.branch);
4645
+ if (!refs.remoteSha) {
4646
+ throw new UserError(`branch "${opts.branch}" is not on origin — a reviewer grant binds the pushed HEAD, so push it first`);
4647
+ }
4648
+ const head = refs.remoteSha.toLowerCase();
4649
+ if (opts.head !== undefined && String(opts.head).toLowerCase() !== head) {
4650
+ throw new UserError(`--head ${String(opts.head).slice(0, 12)} is not origin's tip of "${opts.branch}" (${head.slice(0, 12)}) — the review covers a commit the grant would not bind; re-review the tip`);
4651
+ }
4652
+ const rec = {
4653
+ v: '1', role: ciGrant.REVIEWER_ROLE, reviewer: opts.reviewer, head, red: '0'.repeat(40),
4654
+ verdict: opts.verdict, cures: opts.cures === undefined ? undefined : ciGrant.formatCures(ciGrant.parseCures(opts.cures)),
4655
+ 'not-before': opts.notBefore, 'ci-run': opts.ciRun,
4656
+ };
4657
+ for (const k of Object.keys(rec)) if (rec[k] === undefined || rec[k] === '') delete rec[k];
4658
+ const v0 = ciGrant.validateReviewRecord(rec);
4659
+ if (!v0.valid) throw new UserError(`the review record is invalid: ${v0.problems.join('; ')}`);
4660
+ if (!v0.passing) throw new UserError(`the review says verdict ${rec.verdict} — a grant carrying a failing review is a contradiction; nothing was posted`);
4661
+
4662
+ if (!isGhUsable(repoAbs)) {
4663
+ throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — a CI grant lives on the tracker, visible from any machine to the gate that reads it, and there is deliberately no local-only fallback`);
4664
+ }
4665
+
4666
+ const info = git.ghIssueView(repoAbs, num, ['state', 'labels', 'title']);
4667
+ if (!info) throw new UserError(`could not read #${num} from the tracker — refusing to write a grant blind`);
4668
+ if (info.state !== 'OPEN') throw new UserError(`#${num} is ${info.state} — a grant expires the instant its issue closes`);
4669
+ if (!ciGrant.titleIsTrunkRed(info.title)) {
4670
+ throw new UserError(`#${num}'s title does not start "${ciGrant.TRUNK_RED_TITLE_PREFIX}" — a reviewer CI grant covers only work that is the red trunk's repair`);
4671
+ }
4672
+ const present = git.ghListLabels(repoAbs);
4673
+ if (present && !present.includes(labels.CI_GRANT_LABEL)) {
4674
+ throw new UserError(labels.ciGrantMissingLabelHint(present) || `this repo has no \`${labels.CI_GRANT_LABEL}\` label`);
4675
+ }
4676
+
4677
+ // Trunk red, in ship's sense — the identical classification cmdCiGrantCreate uses (#155).
4678
+ git.git(['fetch', git.remoteFor(repoAbs), trunk], repoAbs);
4679
+ const trunkRun = git.ghRunForSha(repoAbs, trunk);
4680
+ if (!trunkRun) throw new UserError(`could not read ${trunk}'s CI status (gh run list failed) — refusing to grant blind`);
4681
+ const trunkVerdict = classifyCiRun(repoAbs, trunkRun, `${trunk}@${shortSha(trunkRun.sha)}`);
4682
+ if (trunkVerdict.class !== HUMAN_GATED) {
4683
+ throw new UserError(`${trunk} is not red in the sense \`ship\` checks — ${trunkVerdict.detail || 'green'}. Nothing for a grant to exempt.`);
4684
+ }
4685
+ const redSha = trunkRun.sha;
4686
+ const stacking = computeAntiStacking(repoAbs, trunk, true);
4687
+ if (!stacking.ok) throw new UserError(stacking.reason);
4688
+
4689
+ // The branch's own CI, green at the EXACT head the review covers.
4690
+ const evRun = git.ghRunForSha(repoAbs, opts.branch);
4691
+ if (!evRun) throw new UserError(`could not read "${opts.branch}"'s CI status (gh run list failed) — refusing to grant blind`);
4692
+ if (String(evRun.sha || '').toLowerCase() !== head) {
4693
+ throw new UserError(`"${opts.branch}"'s newest CI run is for ${shortSha(evRun.sha)}, not the reviewed head ${shortSha(head)} — wait for CI on the head, then re-run`);
4694
+ }
4695
+ if (!(evRun.status === 'completed' && evRun.conclusion === 'success')) {
4696
+ throw new UserError(`"${opts.branch}" has no completed, successful CI run at ${shortSha(head)} (status=${evRun.status} conclusion=${evRun.conclusion || 'none'}) — a reviewer grant needs the branch green at its exact head`);
4697
+ }
4698
+
4699
+ // Every claimed cure is a red check on trunk at the red sha.
4700
+ const redRunJobs = trunkRedRunJobs(repoAbs, trunk, redSha);
4701
+ const redJobs = redRunJobs === null ? null : ciCure.redJobSet(redRunJobs);
4702
+ const cr = ciGrant.curesAreRed(ciGrant.parseCures(rec.cures), redJobs);
4703
+ if (!cr.ok) throw new UserError(`${cr.reason}; nothing was posted`);
4704
+
4705
+ rec.red = redSha.toLowerCase();
4706
+ const v = ciGrant.validateReviewRecord(rec);
4707
+ if (!v.passing) throw new UserError(`the review record is invalid: ${v.problems.join('; ')}`);
4708
+
4709
+ const editR = git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({}));
4710
+ if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
4711
+ const commentR = git.ghIssueComment(repoAbs, num,
4712
+ ciGrant.reviewGrantCommentBody(opts.branch, trunk, commentHost(repoAbs), nowISO(), rec));
4713
+ if (!commentR.ok) {
4714
+ git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({ clear: true }));
4715
+ throw new UserError(`label applied but the grant comment failed to post (${commentR.stderr.split('\n')[0] || commentR.code}) — rolled the label back so this does not read as granted. Re-run.`);
4716
+ }
4717
+
4718
+ print(`Recorded a ${ciGrant.REVIEWER_ROLE} CI grant on #${num} in ${shortRepo(repoAbs)} — reviewer "${rec.reviewer}", branch "${opts.branch}" @ ${head.slice(0, 12)}.`);
4719
+ print(` Bound to that HEAD and to red ${trunk}@${shortSha(redSha)}: a new commit on either voids it. Cures: ${rec.cures}.`);
4720
+ if (rec['not-before']) print(` Not usable before ${rec['not-before']} (revoke window).`);
4721
+ print(` Revoke any time: COLAB_HUMAN=1 colab ci-grant ${num} --revoke`);
4722
+ return 0;
4723
+ }
4724
+
4290
4725
  function cmdCiGrantCreate(repoAbs, num, opts) {
4291
4726
  if (!opts.branch) {
4292
4727
  throw new UserError('--branch <branch> is required — a grant is bound to one branch, never inferred from the current checkout');
@@ -4367,7 +4802,8 @@ function cmdCiGrantRevoke(repoAbs, num) {
4367
4802
  if (!info) throw new UserError(`could not read #${num} from the tracker`);
4368
4803
  const labelNames = (info.labels || []).map((l) => (l && typeof l === 'object' ? l.name : l));
4369
4804
  const hasLabel = labelNames.includes(labels.CI_GRANT_LABEL);
4370
- const live = ciGrant.liveGrants(info.comments);
4805
+ // Every role (#504): a revoke cancels reviewer grants too, so a reviewer-only issue is not "nothing to revoke".
4806
+ const live = ciGrant.liveGrantRecords(info.comments);
4371
4807
 
4372
4808
  if (!hasLabel && live.length === 0) {
4373
4809
  print(`No live CI grant on #${num} in ${shortRepo(repoAbs)} — nothing to revoke.`);
@@ -4393,7 +4829,7 @@ function cmdCiGrantRevoke(repoAbs, num) {
4393
4829
  }
4394
4830
 
4395
4831
  function cmdCiGrantList(opts) {
4396
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4832
+ const repoAbs = resolveRepoOrCwd(opts);
4397
4833
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4398
4834
  if (!isGhUsable(repoAbs)) {
4399
4835
  throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — cannot list CI grants`);
@@ -4413,14 +4849,15 @@ function cmdCiGrantList(opts) {
4413
4849
  const stale = [];
4414
4850
  for (const h of hits) {
4415
4851
  const info = git.ghIssueView(repoAbs, h.number, ['state', 'labels', 'comments']);
4416
- const live = info ? ciGrant.liveGrants(info.comments) : [];
4852
+ const live = info ? ciGrant.liveGrantRecords(info.comments) : [];
4417
4853
  if (live.length === 0) { stale.push(h.number); continue; }
4418
4854
  const g = live[live.length - 1];
4419
4855
  // Spent: the normal post-ship state — trunk's head has moved past the sha this grant named.
4420
4856
  // Not an error, just informative — distinguishes "still live, awaiting a ship" from "already
4421
4857
  // used (or overtaken by an unrelated trunk change) and inert" without anyone revoking it.
4422
4858
  const spent = currentTrunkSha !== null && g.redSha !== currentTrunkSha;
4423
- grants.push({ issue: h.number, title: h.title, branch: g.branch, redSha: g.redSha, evidenceSha: g.evidenceSha, by: g.login, authorAssociation: g.authorAssociation, at: g.at, spent });
4859
+ const reviewer = g.role !== 'human' ? { role: g.role, reviewer: g.reviewer, head: g.head } : {};
4860
+ grants.push({ issue: h.number, title: h.title, branch: g.branch, redSha: g.redSha, evidenceSha: g.role === 'human' ? g.evidenceSha : g.head, by: g.login, authorAssociation: g.authorAssociation, at: g.at, spent, ...reviewer });
4424
4861
  }
4425
4862
 
4426
4863
  if (opts.json) {
@@ -4432,7 +4869,7 @@ function cmdCiGrantList(opts) {
4432
4869
  return 0;
4433
4870
  }
4434
4871
  print(table(
4435
- grants.map((g) => [String(g.issue), g.branch, shortSha(g.redSha), g.spent ? 'spent' : 'live', g.by || '(unknown)', g.title]),
4872
+ grants.map((g) => [String(g.issue), g.branch, shortSha(g.redSha), g.spent ? 'spent' : 'live', (g.by || '(unknown)') + (g.role ? ` (${g.role} ${g.reviewer})` : ''), g.title]),
4436
4873
  ['ISSUE', 'BRANCH', 'RED SHA', 'STATE', 'GRANTED BY', 'TITLE'],
4437
4874
  ));
4438
4875
  if (stale.length) {
@@ -4500,8 +4937,11 @@ function syncClaims({ prune = false } = {}) {
4500
4937
  if (!git.ghAvailable()) { warn('gh not available — --sync skipped'); return; }
4501
4938
  const st = state.loadState();
4502
4939
  // repos represented locally + repos with a resolvable remote (#301: not necessarily `origin`)
4503
- const repos = new Set(Object.values(st.claims).map((c) => c.repo));
4504
- const cur = git.repoRoot(process.cwd());
4940
+ // #487: every repo here is a MAIN root. This was the writer of the worktree-keyed rows nothing could
4941
+ // release: from inside a linked worktree, repoRoot(cwd) is the worktree, so every assigned issue
4942
+ // was re-added as `<worktree>#N` — a second row beside the real `<mainRoot>#N`, outliving the dir.
4943
+ const repos = new Set(Object.values(st.claims).map((c) => claimHomeRoot(c.repo)).filter(Boolean));
4944
+ const cur = git.mainRepoRoot(process.cwd());
4505
4945
  if (cur) repos.add(cur);
4506
4946
 
4507
4947
  const added = [], removed = [];
@@ -4528,7 +4968,7 @@ function syncClaims({ prune = false } = {}) {
4528
4968
  }
4529
4969
  // local → GH: REMOVE stale local claims ONLY when --prune is given
4530
4970
  if (prune) {
4531
- const localForRepo = Object.entries(st.claims).filter(([k]) => k.startsWith(`${repoAbs}#`));
4971
+ const localForRepo = Object.entries(st.claims).filter(([k]) => claimKeyInRepo(k, repoAbs));
4532
4972
  for (const [key, c] of localForRepo) {
4533
4973
  const num = normIssueNum(c.issue);
4534
4974
  if (!assignedSet.has(num)) {
@@ -4661,7 +5101,7 @@ function cmdPortAlloc(argv) {
4661
5101
  const config = state.loadConfig();
4662
5102
  const count = opts.count ? parseInt(opts.count, 10) : 1;
4663
5103
  if (!Number.isInteger(count) || count < 1) throw new UserError('--count must be a positive integer');
4664
- const explicitRepo = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
5104
+ const explicitRepo = resolveRepoOrCwd(opts);
4665
5105
  const atPorts = parseAtPorts(opts);
4666
5106
 
4667
5107
  // For range resolution, a --worktree owner's repo wins over cwd (its project.yml window applies).
@@ -4708,7 +5148,7 @@ function cmdPortFree(argv) {
4708
5148
  flags: { '-h': 'help', '--help': 'help' },
4709
5149
  });
4710
5150
  if (opts.help) return print(HELP_PORT);
4711
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
5151
+ const repoAbs = resolveRepoOrCwd(opts);
4712
5152
 
4713
5153
  const freed = state.mutate((st) => {
4714
5154
  let targets = [];
@@ -4985,7 +5425,10 @@ function removeWorktreeDir(repoAbs, wtPath) {
4985
5425
  function uncommittedWork(wtPath) {
4986
5426
  if (!wtPath || !fs.existsSync(wtPath)) return { any: false, lines: '', what: '' };
4987
5427
  const tracked = git.dirtyTracked(wtPath);
4988
- const untracked = git.dirtyUntracked(wtPath);
5428
+ // #488: scratch (a plan or brief left in the worktree) is disposable by definition — it must never
5429
+ // be what makes a teardown refuse. Normally info/exclude already hides it; this covers a clone
5430
+ // whose exclude predates the scratch dirs, or a dir configured after the worktree was cut.
5431
+ const untracked = scratchDirs.withoutScratch(git.dirtyUntracked(wtPath));
4989
5432
  return {
4990
5433
  any: !!(tracked || untracked),
4991
5434
  lines: [tracked, untracked].filter(Boolean).join('\n'),
@@ -5260,6 +5703,11 @@ function cmdWorktreeNew(argv) {
5260
5703
  }
5261
5704
  settleTrackerPending(repoAbs, claimedHere.filter((n) => !lostIssues.includes(n)), trackerMissed, { wtName: name, branch });
5262
5705
 
5706
+ // #488: the scratch dirs (plans, briefs) are hidden in the clone's shared info/exclude — one
5707
+ // write covers the main checkout and every worktree, with no per-repo .gitignore diff.
5708
+ // #527: and the worktree subdir itself, or trunk's `git add -A` stages this worktree as a gitlink.
5709
+ ensureScratchExcluded(repoAbs, config);
5710
+
5263
5711
  // 5. optional repo hook (machine-specific steps plug in here)
5264
5712
  const hook = runHook(repoAbs, 'post-create', { wtPath, name, branch, ports: alloc.chosenPorts, trunk, base, issues });
5265
5713
  if (hook.ran && !hook.ok) warn(`post-create hook exited ${hook.code} — worktree was still created; finish setup manually`);
@@ -6231,9 +6679,15 @@ function cmdDoctor(argv) {
6231
6679
  const entry = { repo: shortRepo(repo), label: v.name, verdict: v.verdict,
6232
6680
  total: v.total, open: v.open, members: v.members, deleted: false, error: null };
6233
6681
  if (opts.prune && v.verdict === 'spent') {
6234
- const del = git.ghLabelDelete(repo, v.name);
6235
- entry.deleted = !!del.ok;
6236
- if (!del.ok) entry.error = del.stderr || 'gh label delete failed';
6682
+ // #448: `spent` came from the search-backed listing; confirm through the issues table.
6683
+ const t = groupLabels.teardownSpentGroupLabel(v.name, {
6684
+ searchOpen: [],
6685
+ confirmOpen: (name) => git.ghOpenIssueNumbersByLabel(repo, name),
6686
+ deleteLabel: (name) => git.ghLabelDelete(repo, name),
6687
+ });
6688
+ entry.deleted = t.deleted;
6689
+ if (t.action === 'keep') entry.error = groupLabels.keptReason(v.name, t);
6690
+ else if (!t.deleted) entry.error = t.error;
6237
6691
  }
6238
6692
  report.spentGroupLabels.push(entry);
6239
6693
  }
@@ -6725,9 +7179,10 @@ function measureHeadCandidate(repoAbs, { candidatesAuto, mainRef, lastRelease, o
6725
7179
  const tagsAtSha = tagsR.ok ? tagsR.stdout.split('\n').map((t) => t.trim()).filter(Boolean) : [];
6726
7180
  let runs = null;
6727
7181
  if (isGhUsable(repoAbs)) {
6728
- const r = spawnSync('gh', ['run', 'list', '--branch', 'main', '--commit', sha, '-L', '50', '--json', 'status,conclusion,event,createdAt,updatedAt,workflowName'],
6729
- { cwd: repoAbs, encoding: 'utf8' });
6730
- if (r.status === 0) { try { const j = JSON.parse(r.stdout); runs = Array.isArray(j) ? j : null; } catch (_) { runs = null; } }
7182
+ const r = tracker.forRepo(repoAbs).runList({
7183
+ branch: 'main', commit: sha, limit: 50, fields: ['status', 'conclusion', 'event', 'createdAt', 'updatedAt', 'workflowName'],
7184
+ });
7185
+ runs = Array.isArray(r.data) ? r.data : null;
6731
7186
  }
6732
7187
  const promotion = dualTrunk ? measurePromotion(repoAbs, { sha, trunk, remote, fetched: fetchTrunk }) : null;
6733
7188
  return releaseCut.headCandidateVerdict({
@@ -6763,7 +7218,9 @@ Per tag-gated repo:
6763
7218
  headCandidate #443, where candidates are automatic: { state, flag, detail } — whether the newest
6764
7219
  candidate names main's head. Flags (state untagged, "head not a candidate") when
6765
7220
  head has been green for longer than one CI cycle — the longest suite run at that
6766
- sha — and carries no tag. Other states: named · nothing-owed · not-green ·
7221
+ sha — and carries no tag. Also flags (state no-final, #467) when there is no final tag
7222
+ at all: \`release cut --auto\` refuses every run until a human tags the first version,
7223
+ a stall that otherwise reads green. Other states: named · nothing-owed · not-green ·
6767
7224
  pending (inside one cycle) · not-promotion (trunk: dev, a hotfix head) · unread · off.
6768
7225
  semverSuggestion from Conventional-Commit types since the last tag: a breaking change (! or a
6769
7226
  BREAKING CHANGE: footer) -> major, else feat -> minor, else fix -> patch,
@@ -6775,7 +7232,7 @@ fetch failure does not abort the row — it degrades to whatever is on disk and
6775
7232
  rather than reporting nothing.
6776
7233
 
6777
7234
  Exit code: 0 when nothing is flagged, 1 when at least one repo is (an unpromoted or unreleased
6778
- fix/breaking commit, or a green head that is not a candidate) — same posture as \`colab update\`'s "behind" tally.
7235
+ fix/breaking commit, a green head that is not a candidate, or no final tag at all) — same posture as \`colab update\`'s "behind" tally.
6779
7236
  `;
6780
7237
 
6781
7238
  function cmdReleaseStatus(argv) {
@@ -6824,7 +7281,7 @@ function cmdReleaseStatus(argv) {
6824
7281
  const tableRows = printable.map((r) => {
6825
7282
  const up = r.unpromoted ? `${r.unpromoted.commits}${r.unpromoted.fixFlag ? ' ⚠' : ''}` : '—';
6826
7283
  const un = r.unreleased.tag ? `${r.unreleased.commits}${r.unreleased.fixFlag ? ' ⚠' : ''} (${r.unreleased.days}d since ${r.unreleased.tag})` : 'no tags yet';
6827
- const hc = r.headCandidate ? (r.headCandidate.flag ? '⚠ not a candidate' : r.headCandidate.state) : '—';
7284
+ const hc = r.headCandidate ? (r.headCandidate.flag ? (r.headCandidate.state === 'no-final' ? '⚠ no final' : '⚠ not a candidate') : r.headCandidate.state) : '—';
6828
7285
  return [r.repo, up, un, hc, r.semverSuggestion.bump || '—', r.flag ? '⚠ FLAGGED' : ''];
6829
7286
  });
6830
7287
  print(table(tableRows, ['REPO', 'UNPROMOTED', 'UNRELEASED', 'HEAD', 'SUGGEST', '']));
@@ -6841,7 +7298,7 @@ function cmdReleaseStatus(argv) {
6841
7298
  }
6842
7299
  print('');
6843
7300
  if (flagged.length) {
6844
- print(`${flagged.length} repo(s) FLAGGED — a fix or breaking commit is sitting unreleased/unpromoted, or a green head is not a candidate:`);
7301
+ print(`${flagged.length} repo(s) FLAGGED — a fix or breaking commit is sitting unreleased/unpromoted, a green head is not a candidate, or there is no final for candidates to follow:`);
6845
7302
  for (const r of flagged) print(` ${r.repo}${r.headCandidate && r.headCandidate.flag ? ` — ${r.headCandidate.detail}` : ''}`);
6846
7303
  print('Who cuts the tag follows the release rung of CONVENTIONS §6 — this only measures the gap.');
6847
7304
  } else {
@@ -7287,6 +7744,7 @@ const HELP_ADOPT = `colab adopt [--repo <path>] [--json] [--no-verify] [--axis a
7287
7744
  [--writes <free|direct|isolated>] [--channels <c1,c2,...>]
7288
7745
  [--production <url>|none] [--deploy <push-main|tag|manual|none>]
7289
7746
  [--stack "<text>"] [--answered-by <name>] [--reason "<text>"]
7747
+ [--fork | --no-fork] [--autonomy <manual|auto-trunk>] [--land]
7290
7748
 
7291
7749
  Detects what a repo already states in .github/project.yml, ASKS a human only what could not be
7292
7750
  detected (flags, or a forced multiple-choice menu at a TTY — every row is a numbered choice,
@@ -7294,6 +7752,18 @@ answered by its number OR its literal value), DERIVES the rest, and WRITES the d
7294
7752
  act — append-only, never touching a byte already there. A complete descriptor just reports
7295
7753
  (write nothing, exit 0); re-answer one row on purpose with --axis.
7296
7754
 
7755
+ ONLY THE GATING ROWS ARE ASKED (#533): deploy/production and exposure. room, writes and channels
7756
+ are optional and legal absent — never prompted for; the report names them in one line with the
7757
+ \`--axis\` command that answers each later, and their own flag still answers one in the same run.
7758
+ After deploy: none, production is not asked again (null follows; --deploy none alone implies it).
7759
+
7760
+ A SINGLE TRUNK, ANY SPELLING (#522): exposure none (and released with production null, and the
7761
+ legacy tier B) need ONE long-lived branch, not one named "main" — an existing master default
7762
+ adopts as-is. A "main" beside a non-main trunk is the two-branch shape and is refused (exit 5).
7763
+ At a terminal the exposure answer is checked against that shape when given, and re-asked with
7764
+ the reason. When a human must finish (the gate below), the FIRST line printed is the one
7765
+ command to run, every answer this run had already filled in.
7766
+
7297
7767
  --writes accepts free (coexistence, the default), direct (an attended human may commit straight
7298
7768
  to trunk; DECLARED today, its runtime is DEFERRED — see CONVENTIONS.md §2, "writes: direct —
7299
7769
  declared today, runtime deferred"), or isolated (vetoes trunk-direct outright, human or not).
@@ -7308,8 +7778,41 @@ accepted and reads as free — no adopter's descriptor breaks, and none is re-as
7308
7778
  --answered-by N who is answering, alongside COLAB_HUMAN=1 (see THE HUMAN GATE below)
7309
7779
  --reason "..." required alongside a lowered or evidence-contradicted exposure answer;
7310
7780
  written into the file, next to the key it justifies
7311
-
7312
- Any answer flag (--room/--exposure/--writes/--channels/--production/--deploy/--stack) makes the
7781
+ --fork / --no-fork
7782
+ a repo you own that tracks an upstream you don't (#449) is DETECTED — a
7783
+ remote named \`upstream\` whose URL differs from origin's. Assert it with
7784
+ --fork when the upstream remote is named otherwise; deny it with --no-fork.
7785
+ On a fork, step 5 of the remaining list is the append-only Conventions block
7786
+ (never the thin-shell conversion), the upstream's own agent workflow is
7787
+ named, and a new CLAUDE.md gets no AGENTS.md stub (CONVENTIONS.md §9,
7788
+ "A fork of an upstream")
7789
+
7790
+ THE AUTONOMY GRANT AND --land (#481) — so a new repo's first branch is not hand-merged:
7791
+
7792
+ --autonomy auto-trunk records the maintainer's grant (project.yml autonomy:) with the same
7793
+ provenance comment as every answer. It EXPANDS permission (an agent may
7794
+ then complete Phase B through \`colab ship\`), so it carries the writes:
7795
+ direct bar: interactive TTY, OR COLAB_HUMAN=1 AND --answered-by <name>
7796
+ (exit 3 otherwise). Refused with ceremony: light (exit 5). manual (the
7797
+ default) is never gated. Append-only: a different value already declared
7798
+ is refused (exit 5) — change it by hand.
7799
+ --land commits what THIS run wrote — the descriptor, plus the thin-shell
7800
+ CLAUDE.md/AGENTS.md when written now — straight to trunk as its own
7801
+ commit, then pushes origin/<trunk>. It is the human's adoption act, not
7802
+ an agent's: COLAB_HUMAN=1 AND --answered-by are required, no TTY
7803
+ substitute (exit 3). It runs only on the checkout standing ON trunk, never
7804
+ with --local, and refuses before writing anything when origin's trunk is
7805
+ ahead (pull first). Run without new answers, it lands a descriptor an
7806
+ earlier adopt left uncommitted. No origin remote: commits only.
7807
+
7808
+ The shape it exists for: \`colab ship\` judges a branch's autonomy by the descriptor trunk
7809
+ carries. Land it first, and the follow-up branch (CI workflow, guards, docs) ships through the
7810
+ normal lane under the grant — no human merge of the adoption branch.
7811
+
7812
+ COLAB_HUMAN=1 colab adopt --exposure self --stack node --autonomy auto-trunk \\
7813
+ --answered-by "<name>" --land
7814
+
7815
+ Any answer flag (--room/--exposure/--writes/--channels/--production/--deploy/--stack/--autonomy) makes the
7313
7816
  whole run NON-INTERACTIVE — it never half-prompts. With no answer flags and no TTY, and something
7314
7817
  is still missing, this refuses in under a second, naming exactly which flags would answer it —
7315
7818
  never hangs waiting on stdin nobody is at.
@@ -7399,7 +7902,8 @@ files is not an option (CONVENTIONS.md §9, "Working in a repo you don't own"):
7399
7902
 
7400
7903
  1. refuses if .github/project.yml is TRACKED (then the repo is adopted — use plain adopt), if
7401
7904
  --trunk is missing, or if --trunk names the owner's own default branch;
7402
- 2. appends /.github/project.yml, /CLAUDE.local.md, /.claude/plans/ and the worktree subdir
7905
+ 2. appends /.github/project.yml, /CLAUDE.local.md, the scratch dirs (/.plans/, /.briefs/,
7906
+ legacy /.claude/plans/ — #488) and the worktree subdir
7403
7907
  (/.worktrees/ by default — the owner's .gitignore does not hide it) to .git/info/exclude (the
7404
7908
  shared common dir — never .gitignore, which is itself a tracked file) BEFORE writing, and
7405
7909
  keeps them even if a later check refuses (idempotent, local, hides nothing that exists);
@@ -7415,7 +7919,7 @@ files is not an option (CONVENTIONS.md §9, "Working in a repo you don't own"):
7415
7919
  block, topic, register, autopilot) and why.
7416
7920
 
7417
7921
  Boundary: adopt writes the descriptor and nothing else — no labels, no topic, no CI template, no
7418
- \`colab register\`, and it never commits. One exception (#417): on a repo with no descriptor before
7922
+ \`colab register\`, and it never commits unless --land asks it to (#481). One exception (#417): on a repo with no descriptor before
7419
7923
  the run and no CLAUDE.md, plain adopt also writes the thin-shell CLAUDE.md (\`@AGENTS.md\` + the
7420
7924
  filled Conventions block) and an AGENTS.md stub if none exists; an existing CLAUDE.md is never
7421
7925
  touched, and --local never writes either. It ends with the machine-readable
@@ -7436,7 +7940,7 @@ const ADOPT_ROW_ORDER = ['tier', 'room', 'exposure', 'writes', 'channels'];
7436
7940
  * read from a remote's HEAD, and the report says so (`detected.trunk.source`), never presented
7437
7941
  * as though it were.
7438
7942
  */
7439
- function adoptGitExtras(repoAbs) {
7943
+ function adoptGitExtras(repoAbs, opts = {}) {
7440
7944
  let trunk = git.detectTrunk(repoAbs);
7441
7945
  let trunkSource = trunk ? 'origin-head' : null;
7442
7946
  if (!trunk) {
@@ -7450,7 +7954,48 @@ function adoptGitExtras(repoAbs) {
7450
7954
  const hooksPath = hp.ok && hp.stdout ? hp.stdout : null;
7451
7955
  let hooksDirFiles = [];
7452
7956
  try { hooksDirFiles = fs.readdirSync(path.join(repoAbs, '.githooks')); } catch (_) { /* absent */ }
7453
- return { trunk, trunkSource, hooksPath, hooksDirFiles };
7957
+ // #449: `git ls-files` for the migrations candidate scan (adopt never asks `migrations:`).
7958
+ const ls = git.git(['ls-files'], repoAbs);
7959
+ const trackedFiles = ls.ok ? ls.stdout.split('\n').filter(Boolean) : undefined;
7960
+ // #483: the fork's own owner, from origin's URL — what an inherited CODEOWNERS team is compared to.
7961
+ const originUrl = git.git(['remote', 'get-url', 'origin'], repoAbs);
7962
+ const ownOrg = originUrl.ok ? codeowners.remoteOwner(originUrl.stdout) : null;
7963
+ return { trunk, trunkSource, hooksPath, hooksDirFiles, trackedFiles, fork: adoptDetectFork(repoAbs, opts), ownOrg, branches: adoptBranchList(repoAbs) };
7964
+ }
7965
+
7966
+ /** #522: every branch name visible here — refs/heads ∪ refs/remotes/<any>/<name> — the same union
7967
+ * audit/audit.mjs's `branches()` reads, so the single-trunk rule (tools/lib/exposure-shape.js
7968
+ * `singleTrunkViolation`) answers identically on both sides: adopt never writes what the audit
7969
+ * then fails. null when git cannot list refs (the rule then fails closed to trunk "main"). */
7970
+ function adoptBranchList(repoAbs) {
7971
+ const r = git.git(['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes'], repoAbs);
7972
+ if (!r.ok) return null;
7973
+ const names = new Set();
7974
+ for (const ref of r.stdout.split('\n').map((x) => x.trim()).filter(Boolean)) {
7975
+ if (ref.startsWith('refs/heads/')) names.add(ref.slice('refs/heads/'.length));
7976
+ else if (ref.startsWith('refs/remotes/')) {
7977
+ const rest = ref.slice('refs/remotes/'.length);
7978
+ const name = rest.slice(rest.indexOf('/') + 1);
7979
+ if (rest.includes('/') && name && name !== 'HEAD') names.add(name);
7980
+ }
7981
+ }
7982
+ return [...names];
7983
+ }
7984
+
7985
+ /**
7986
+ * #449 — is this a repo you own that tracks an upstream you don't? DETECTED, never asked (§9):
7987
+ * a remote named `upstream` whose URL differs from origin's (the conventional name for the repo a
7988
+ * fork tracks). `--fork` asserts it when the upstream remote is named otherwise; `--no-fork`
7989
+ * denies it when a remote named `upstream` means something else. Returns null when not a fork.
7990
+ */
7991
+ function adoptDetectFork(repoAbs, opts = {}) {
7992
+ if (opts.noFork) return null;
7993
+ const up = git.git(['remote', 'get-url', 'upstream'], repoAbs);
7994
+ const origin = git.git(['remote', 'get-url', 'origin'], repoAbs);
7995
+ const upUrl = up.ok && up.stdout ? up.stdout : null;
7996
+ if (upUrl && !(origin.ok && origin.stdout === upUrl)) return { remote: 'upstream', url: upUrl, source: opts.fork ? 'flag' : 'upstream-remote' };
7997
+ if (opts.fork) return { remote: null, url: null, source: 'flag' };
7998
+ return null;
7454
7999
  }
7455
8000
 
7456
8001
  /** The `{ readFile, listDir, tags }` adapter tools/lib/adopt.js asks for — matching the local
@@ -7504,6 +8049,30 @@ function gitExcludePath(repoAbs) {
7504
8049
  return path.join(r.stdout, 'info', 'exclude');
7505
8050
  }
7506
8051
 
8052
+ /**
8053
+ * #488: append the scratch-dir exclude lines (scratch-dirs.js `excludeLines`) to the clone's shared
8054
+ * info/exclude, idempotently. Best-effort: a failure warns and never blocks the caller.
8055
+ * #527: `config` given → the worktree subdir's line too (`worktreeExcludeLine`), so whatever creates
8056
+ * the default worktree dir also hides it — an adopted repo's `.gitignore` has never heard of it.
8057
+ */
8058
+ function ensureScratchExcluded(repoAbs, config = null) {
8059
+ const excludeFile = gitExcludePath(repoAbs);
8060
+ if (!excludeFile) return [];
8061
+ let before = null;
8062
+ try { before = fs.readFileSync(excludeFile, 'utf8'); } catch (_) { /* absent */ }
8063
+ const lines = scratchDirs.excludeLines();
8064
+ const wtLine = config ? scratchDirs.worktreeExcludeLine(worktreeSubdir(config)) : null;
8065
+ if (wtLine && !lines.includes(wtLine)) lines.push(wtLine);
8066
+ const missing = localAdopt.missingExcludeLines(before, lines);
8067
+ if (!missing.length) return [];
8068
+ try {
8069
+ fs.mkdirSync(path.dirname(excludeFile), { recursive: true });
8070
+ const sep = before && !before.endsWith('\n') ? '\n' : '';
8071
+ fs.appendFileSync(excludeFile, sep + missing.join('\n') + '\n');
8072
+ } catch (e) { warn(`could not hide the scratch dirs in ${excludeFile}: ${e.message}`); return []; }
8073
+ return missing;
8074
+ }
8075
+
7507
8076
  function gitTracks(repoAbs, rel) {
7508
8077
  return git.git(['ls-files', '--error-unmatch', '--', rel], repoAbs).ok;
7509
8078
  }
@@ -7687,6 +8256,15 @@ function printAdoptReport(report, repoAbs, verify, localFinish) {
7687
8256
  print(`detected trunk: ${t.detected || '(unknown)'}${trunkSourceNote}${t.declared !== null ? ` (declared: ${t.declared}${t.agree === false ? ' ⚠ disagrees with detected' : ''})` : ''}`);
7688
8257
  print(`stack candidates: ${report.detected.stackCandidates.length ? report.detected.stackCandidates.join(', ') : '(none found)'}`);
7689
8258
  print(`declared ports: ${fmtVal(report.detected.ports)}`);
8259
+ const optLine = adopt.optionalRowsLine(report.optionalUnanswered); // #533
8260
+ if (optLine) print(optLine);
8261
+ if (report.fork) print(`fork of an upstream: yes — ${report.fork.source === 'flag' ? '--fork' : `remote "${report.fork.remote}" ${report.fork.url}`} (step 5 is the append-only block, §9 "A fork of an upstream")`);
8262
+ if (report.inheritedCodeowners) {
8263
+ const ic = report.inheritedCodeowners;
8264
+ print(`⚠ inherited CODEOWNERS: ${ic.path} names ${ic.teams.join(', ')} — team(s) of an org other than ${ic.ownOrg}. ` +
8265
+ 'colab ship ignores them on this fork, so they gate no landing here; write the fork\'s own owners into that file ' +
8266
+ '(a fork patch) if some paths here should need a review (§2 "Core paths", #483)');
8267
+ }
7690
8268
  print(`legacy tier letter, derived from (production, deploy): ${report.legacyTierLetter ?? '(undetermined — production is set but deploy matches none of push-main/tag/manual)'}`);
7691
8269
  print('');
7692
8270
  print('Derived consequences:');
@@ -7755,6 +8333,8 @@ function adoptAnswersFromFlags(opts, cfg, axesToAsk, forcedAxes) {
7755
8333
  if (!adopt.VALID_DEPLOY.has(opts.deploy)) throw new UserError(`--deploy must be one of: ${[...adopt.VALID_DEPLOY].join(', ')}`);
7756
8334
  values.deploy = opts.deploy;
7757
8335
  flags.push('--deploy');
8336
+ // #533: deploy: none already says nothing is live — production: null follows, never re-asked.
8337
+ if (opts.deploy === 'none' && opts.production === undefined && eligible('production', 'tier')) values.production = null;
7758
8338
  }
7759
8339
  if (flags.length) answers.tier = { values, mode: 'flag', flags };
7760
8340
  }
@@ -7801,7 +8381,9 @@ async function askMenu(rl, axis, promptFn) {
7801
8381
  if (resolved.ok) return resolved;
7802
8382
  process.stdout.write(` ${resolved.message}\n`);
7803
8383
  }
7804
- throw new UserError(`${axis}: no valid answer after one re-prompt`);
8384
+ throw new UserError(`${axis}: no valid answer after one re-prompt — nothing was written. Run \`colab adopt --axis ${axis}\` ` +
8385
+ `to be asked again, or pass the value directly: \`colab adopt ${axis === 'tier' ? '--deploy' : `--${axis}`} <value>\` ` +
8386
+ `(\`colab adopt --help\` lists them).`);
7805
8387
  }
7806
8388
 
7807
8389
  /**
@@ -7818,7 +8400,7 @@ async function askMenu(rl, axis, promptFn) {
7818
8400
  * URL itself asked only on "yes" — this keeps every axis forced-choice-shaped without pretending
7819
8401
  * a URL belongs to an enum.
7820
8402
  */
7821
- async function adoptAskInteractive(rl, axesToAsk, cfg) {
8403
+ async function adoptAskInteractive(rl, axesToAsk, cfg, checkExposure) {
7822
8404
  const answers = {};
7823
8405
  for (const axis of axesToAsk) {
7824
8406
  const q = adopt.QUESTIONS.find((x) => x.axis === axis);
@@ -7829,13 +8411,16 @@ async function adoptAskInteractive(rl, axesToAsk, cfg) {
7829
8411
  process.stdout.write(`${adopt.renderMenu('tier')}\n`);
7830
8412
  return rlAsk(rl, ' deploy: ');
7831
8413
  });
7832
- process.stdout.write(' 1) no deploy target exists today\n 2) yes — enter the URL\n');
7833
- const existsRaw = (await rlAsk(rl, ' production: ')).trim();
7834
8414
  let prod = null;
7835
- if (existsRaw === '2' || existsRaw === 'yes') {
7836
- prod = (await rlAsk(rl, ' URL: ')).trim() || null;
7837
- } else if (existsRaw !== '1' && existsRaw !== 'no') {
7838
- throw new UserError('production: choose 1 (no deploy target exists today) or 2 (yes — enter the URL)');
8415
+ // #533: deploy: none already answered "nothing is live" — asking production again is noise.
8416
+ if (depChoice.value !== 'none') {
8417
+ process.stdout.write(' 1) no deploy target exists today\n 2) yes — enter the URL\n');
8418
+ const existsRaw = (await rlAsk(rl, ' production: ')).trim();
8419
+ if (existsRaw === '2' || existsRaw === 'yes') {
8420
+ prod = (await rlAsk(rl, ' URL: ')).trim() || null;
8421
+ } else if (existsRaw !== '1' && existsRaw !== 'no') {
8422
+ throw new UserError('production: choose 1 (no deploy target exists today) or 2 (yes — enter the URL)');
8423
+ }
7839
8424
  }
7840
8425
  answers.tier = { values: { production: prod, deploy: depChoice.value }, mode: 'interactive' };
7841
8426
  } else if (axis === 'channels') {
@@ -7845,12 +8430,25 @@ async function adoptAskInteractive(rl, axesToAsk, cfg) {
7845
8430
  });
7846
8431
  answers.channels = { values: { channels: resolved.value }, mode: 'interactive' };
7847
8432
  } else if (axis === 'exposure') {
7848
- const resolved = await askMenu(rl, 'exposure', () => {
7849
- process.stdout.write(`${adopt.renderMenu('exposure')}\n`);
7850
- return rlAsk(rl, ' choice: ');
7851
- });
7852
- if (resolved.skip) continue; // decline — the fallback tier derivation picks this up
7853
- answers.exposure = { values: { exposure: resolved.value }, mode: 'interactive' };
8433
+ // #522: the repo-shape check runs HERE, at answer time — a refusal re-asks with its reason,
8434
+ // instead of surfacing after every other question with nothing written.
8435
+ let chosen = null;
8436
+ for (let attempt = 0; attempt < 2 && !chosen; attempt++) {
8437
+ const resolved = await askMenu(rl, 'exposure', () => {
8438
+ process.stdout.write(`${adopt.renderMenu('exposure')}\n`);
8439
+ return rlAsk(rl, ' choice: ');
8440
+ });
8441
+ if (resolved.skip) { chosen = resolved; break; }
8442
+ const problem = checkExposure ? checkExposure(resolved.value, answers) : null;
8443
+ if (!problem) { chosen = resolved; break; }
8444
+ process.stdout.write(` ✗ ${problem}\n choose again (or skip):\n`);
8445
+ }
8446
+ // #532: this refusal comes after a long interaction, so it names the way through, not just the stop.
8447
+ if (!chosen) throw new UserError('exposure: no answer this repo\'s shape supports after one re-prompt — nothing was written. ' +
8448
+ 'Each "✗" above says why its value was refused. Run `colab adopt --axis exposure` and pick a value it accepts, ' +
8449
+ 'or `colab adopt --exposure <value>` non-interactively; choosing "skip" leaves exposure unanswered for now.');
8450
+ if (chosen.skip) continue; // decline — the fallback tier derivation picks this up
8451
+ answers.exposure = { values: { exposure: chosen.value }, mode: 'interactive' };
7854
8452
  } else {
7855
8453
  // room, writes — plain single-choice menus, no skip.
7856
8454
  const resolved = await askMenu(rl, axis, () => {
@@ -7863,11 +8461,41 @@ async function adoptAskInteractive(rl, axesToAsk, cfg) {
7863
8461
  return answers;
7864
8462
  }
7865
8463
 
8464
+ /** #522: this run's answers as the ordered flag list `adopt.humanAdoptCommand` prints — what the
8465
+ * human pastes to finish the same adoption with the gate satisfied. */
8466
+ function adoptReplayFlags(opts, answers) {
8467
+ const flags = [];
8468
+ if (opts.repo !== undefined) flags.push(['--repo', opts.repo]);
8469
+ const t = answers.tier && answers.tier.values;
8470
+ if (t && 'production' in t) flags.push(['--production', t.production === null ? 'none' : t.production]);
8471
+ if (t && 'deploy' in t) flags.push(['--deploy', t.deploy]);
8472
+ if (answers.exposure) flags.push(['--exposure', answers.exposure.values.exposure]);
8473
+ if (answers.room) flags.push(['--room', answers.room.values.room]);
8474
+ if (answers.writes) flags.push(['--writes', answers.writes.values.writes]);
8475
+ if (answers.channels) flags.push(['--channels', answers.channels.values.channels.join(',')]);
8476
+ if (opts.stack !== undefined) flags.push(['--stack', opts.stack]);
8477
+ if (opts.autonomy !== undefined) flags.push(['--autonomy', opts.autonomy]);
8478
+ if (opts.reason !== undefined) flags.push(['--reason', opts.reason]);
8479
+ if (opts.answeredBy) flags.push(['--answered-by', opts.answeredBy]);
8480
+ if (opts.land) flags.push(['--land', true]);
8481
+ return flags;
8482
+ }
8483
+
8484
+ /** #522: the same command shape for a run that had no answers at all — placeholders per asked row. */
8485
+ function adoptAskedFlagPlaceholders(axesToAsk, stackUnresolvable) {
8486
+ const flags = [];
8487
+ if (axesToAsk.includes('tier')) flags.push(['--production', '<url>|none'], ['--deploy', '<none|tag|manual|push-main>']);
8488
+ if (axesToAsk.includes('exposure')) flags.push(['--exposure', '<none|self|live|released>']);
8489
+ for (const a of ['room', 'writes', 'channels']) if (axesToAsk.includes(a)) flags.push([`--${a}`, `<${a}>`]);
8490
+ if (stackUnresolvable) flags.push(['--stack', '<text>']);
8491
+ return flags;
8492
+ }
8493
+
7866
8494
  /** The `EXPOSURE_SHAPE`/falsifier context, built from EFFECTIVE production/deploy — accounting
7867
8495
  * for a `tier`-axis answer resolved in THIS SAME run, not only what was already on record, so
7868
8496
  * declaring production+deploy and exposure together in one invocation validates against each
7869
8497
  * other rather than the pre-write snapshot. */
7870
- function adoptShapeCtx(cfg, tierAnswer, trunk, workflows, io) {
8498
+ function adoptShapeCtx(cfg, tierAnswer, trunk, workflows, io, branches) {
7871
8499
  const effProduction = tierAnswer ? tierAnswer.values.production : (Object.prototype.hasOwnProperty.call(cfg, 'production') ? cfg.production : null);
7872
8500
  const effDeploy = tierAnswer ? tierAnswer.values.deploy : (Object.prototype.hasOwnProperty.call(cfg, 'deploy') ? cfg.deploy : null);
7873
8501
  const evidence = consumerEvidence.consumerEvidence(io, workflows);
@@ -7875,7 +8503,7 @@ function adoptShapeCtx(cfg, tierAnswer, trunk, workflows, io) {
7875
8503
  const hasProduction = effProduction !== null && effProduction !== undefined && effProduction !== '';
7876
8504
  const runbook = Object.prototype.hasOwnProperty.call(cfg, 'runbook') ? cfg.runbook : null;
7877
8505
  const hasRunbook = !!(runbook && io.readFile(String(runbook).trim().replace(/^\.\//, '')) !== null);
7878
- return { trunk, hasProduction, deploy: effDeploy, hasDeployWorkflow, hasRunbook, effProduction, effDeploy };
8506
+ return { trunk, hasProduction, deploy: effDeploy, hasDeployWorkflow, hasRunbook, effProduction, effDeploy, branches: branches === undefined ? null : branches };
7879
8507
  }
7880
8508
 
7881
8509
  async function cmdAdopt(argv) {
@@ -7884,15 +8512,20 @@ async function cmdAdopt(argv) {
7884
8512
  '--repo': 'repo', '--axis': 'axis', '--room': 'room', '--exposure': 'exposure',
7885
8513
  '--writes': 'writes', '--channels': 'channels', '--production': 'production',
7886
8514
  '--deploy': 'deploy', '--stack': 'stack', '--answered-by': 'answeredBy', '--reason': 'reason',
7887
- '--trunk': 'trunk',
8515
+ '--trunk': 'trunk', '--autonomy': 'autonomy',
7888
8516
  },
7889
- flags: { '--json': 'json', '--no-verify': 'noVerify', '--local': 'local', '--no-labels': 'noLabels', '-h': 'help', '--help': 'help' },
8517
+ flags: { '--json': 'json', '--no-verify': 'noVerify', '--local': 'local', '--no-labels': 'noLabels', '--fork': 'fork', '--no-fork': 'noFork', '--land': 'land', '-h': 'help', '--help': 'help' },
7890
8518
  });
7891
8519
  if (opts.help) return print(HELP_ADOPT);
8520
+ if (opts.fork && opts.noFork) throw new UserError('--fork and --no-fork contradict each other — pass one');
7892
8521
  if (opts.trunk !== undefined && !opts.local) {
7893
8522
  throw new UserError('--trunk only means something with --local — on an ordinary adoption trunk is DETECTED, never asked (CONVENTIONS.md §9)');
7894
8523
  }
7895
8524
  if (opts.noLabels && !opts.local) throw new UserError('--no-labels only means something with --local — plain adopt never touches labels');
8525
+ if (opts.land && opts.local) throw new UserError('--land cannot combine with --local — a local-only descriptor is never committed (CONVENTIONS.md §9)');
8526
+ if (opts.autonomy !== undefined && !adopt.VALID_AUTONOMY.has(opts.autonomy)) {
8527
+ throw new UserError(`--autonomy must be one of: ${[...adopt.VALID_AUTONOMY].join(', ')} (got ${JSON.stringify(opts.autonomy)})`);
8528
+ }
7896
8529
 
7897
8530
  // --local (#393): the descriptor is machine state, not a committable source file — it lives in
7898
8531
  // the MAIN checkout (where every worktree's `colab` call reads project.yml from, via
@@ -7903,8 +8536,14 @@ async function cmdAdopt(argv) {
7903
8536
  local = adoptLocalPrepare(repoAbs, opts);
7904
8537
  if (local.exit !== undefined) return local.exit;
7905
8538
  }
8539
+ // #527: a repo adopted before `worktree new` hid its own dir gets the same exclude lines here —
8540
+ // machine-local (info/exclude), idempotent, never a committed diff. --local already wrote them.
8541
+ if (!opts.local) {
8542
+ const hidden = ensureScratchExcluded(repoAbs, state.loadConfig());
8543
+ if (hidden.length && !opts.json) print(`✓ hid ${hidden.join(' ')} in .git/info/exclude (machine-local)`);
8544
+ }
7906
8545
  const io = adoptIo(repoAbs);
7907
- const extra = adoptGitExtras(repoAbs);
8546
+ const extra = adoptGitExtras(repoAbs, opts);
7908
8547
  if (local) { extra.trunk = local.trunk; extra.trunkSource = 'local-integration'; }
7909
8548
  const report = adopt.detect(io, extra);
7910
8549
  const cfg = report.cfg;
@@ -7916,16 +8555,45 @@ async function cmdAdopt(argv) {
7916
8555
  if (!adopt.ROW_NAMES.includes(a)) throw new UserError(`Unknown --axis "${a}" — expected one of: ${adopt.ROW_NAMES.join(', ')}`);
7917
8556
  }
7918
8557
  const forcedAxes = new Set(requestedAxes);
7919
- let axesToAsk = adopt.ROW_NAMES.filter((a) => forcedAxes.has(a) || adopt.axisMissing(cfg, a));
8558
+ // #533: a fresh adoption asks only the rows that change a gate (production/deploy, exposure);
8559
+ // room/writes/channels are asked only when forced (--axis) or answered by their flag.
8560
+ const flagAxes = new Set();
8561
+ if (opts.production !== undefined || opts.deploy !== undefined) flagAxes.add('tier');
8562
+ for (const a of ['room', 'exposure', 'writes', 'channels']) if (opts[a] !== undefined) flagAxes.add(a);
8563
+ let axesToAsk = adopt.axesToAsk(cfg, forcedAxes, flagAxes);
7920
8564
  // --local re-run (#393): once exposure is on record, a bare `adopt --local` (no answer flags, no
7921
8565
  // --axis) is the idempotent re-apply — exclude lines, stub, labels, checkout — never a prompt for
7922
8566
  // the optional rows (room/writes/channels), which --local leaves to the operator by design.
7923
8567
  const localAnswerFlag = ['room', 'exposure', 'writes', 'channels', 'production', 'deploy', 'stack'].some((k) => opts[k] !== undefined);
7924
8568
  if (local && !localAnswerFlag && !requestedAxes.length && axisAuthority.axisOfRecord(cfg).source === 'exposure') axesToAsk = [];
7925
8569
 
8570
+ const isTTY = !!(process.stdin.isTTY && process.stdout.isTTY);
8571
+ const colabHuman = process.env.COLAB_HUMAN === '1';
8572
+
8573
+ // #481: --land preflight — every refusal here happens BEFORE anything is written, like the gates.
8574
+ let landTrunk = null;
8575
+ if (opts.land) {
8576
+ landTrunk = cfg.trunk ? String(cfg.trunk) : (extra.trunk || null);
8577
+ const cur = git.git(['symbolic-ref', '--short', 'HEAD'], repoAbs);
8578
+ const lv = adopt.landVerdict({ local: !!opts.local, colabHuman, answeredBy: opts.answeredBy || null,
8579
+ trunk: landTrunk, currentBranch: cur.ok && cur.stdout ? cur.stdout : null });
8580
+ if (!lv.ok) { warn(lv.message); return lv.exitCode; }
8581
+ const behind = adoptLandBehind(repoAbs, landTrunk);
8582
+ if (behind) { warn(behind); return 1; }
8583
+ }
8584
+
8585
+ // #481: --autonomy — the maintainer's grant, gated like writes: direct (it expands permission).
8586
+ let autonomyWrite = false;
8587
+ if (opts.autonomy !== undefined) {
8588
+ const av = adopt.autonomyGateVerdict({ autonomy: opts.autonomy, current: cfg.autonomy, ceremony: cfg.ceremony,
8589
+ isTTY, colabHuman, answeredBy: opts.answeredBy || null });
8590
+ if (!av.ok) { warn(av.message); return av.exitCode; }
8591
+ autonomyWrite = av.write;
8592
+ }
8593
+
7926
8594
  // Already complete (and nothing forced): report, write nothing, exit 0 — except the one key a
7927
8595
  // bare --local re-run still owes (#405): the `owner:` block, for a clone adopted before it existed.
7928
- if (axesToAsk.length === 0 && opts.stack === undefined) {
8596
+ if (axesToAsk.length === 0 && opts.stack === undefined && !autonomyWrite) {
7929
8597
  const backfill = localOwnerEntry(local, cfg, today());
7930
8598
  if (backfill) {
7931
8599
  fs.writeFileSync(descriptorFile, adopt.renderDescriptor(rawTextBefore, [backfill]));
@@ -7933,9 +8601,12 @@ async function cmdAdopt(argv) {
7933
8601
  }
7934
8602
  const verify = opts.noVerify ? null : adoptVerify(repoAbs);
7935
8603
  const lf = local ? adoptLocalFinish(repoAbs, local, opts) : undefined;
7936
- if (opts.json) { print(JSON.stringify({ repo: repoAbs, ...report, verify, ...(backfill ? { written: [{ key: backfill.key, value: backfill.value }] } : {}), local: lf }, null, 2)); return lf && !lf.ok ? 1 : 0; }
8604
+ const land = opts.land ? adoptLand(repoAbs, landTrunk, ['.github/project.yml'], opts.answeredBy) : undefined;
8605
+ const rc = (lf && !lf.ok) || (land && !land.ok) ? 1 : 0;
8606
+ if (opts.json) { print(JSON.stringify({ repo: repoAbs, ...report, verify, ...(backfill ? { written: [{ key: backfill.key, value: backfill.value }] } : {}), local: lf, land }, null, 2)); return rc; }
7937
8607
  printAdoptReport(report, repoAbs, verify, lf);
7938
- return lf && !lf.ok ? 1 : 0;
8608
+ printAdoptLand(land);
8609
+ return rc;
7939
8610
  }
7940
8611
 
7941
8612
  // `trunk` is DETECTED, never asked — no answer flag can supply it, and asking a human "what is
@@ -7950,9 +8621,9 @@ async function cmdAdopt(argv) {
7950
8621
  return 1;
7951
8622
  }
7952
8623
 
7953
- const answerFlagKeys = ['room', 'exposure', 'writes', 'channels', 'production', 'deploy', 'stack'];
8624
+ // --autonomy counts as an answer flag (#481): it makes the run non-interactive, never half-prompted.
8625
+ const answerFlagKeys = ['room', 'exposure', 'writes', 'channels', 'production', 'deploy', 'stack', 'autonomy'];
7954
8626
  const anyAnswerFlagGiven = answerFlagKeys.some((k) => opts[k] !== undefined);
7955
- const isTTY = !!(process.stdin.isTTY && process.stdout.isTTY);
7956
8627
 
7957
8628
  // `stack` is REQUIRED by the audit but free-form, so it cannot always be detected — a
7958
8629
  // manifest-less repo (a docs-only repo; this handbook's own shape) has zero candidates.
@@ -7967,7 +8638,8 @@ async function cmdAdopt(argv) {
7967
8638
  let stackAnsweredInteractively = false;
7968
8639
  if (axesToAsk.length === 0) {
7969
8640
  answers = {};
7970
- } else if (anyAnswerFlagGiven) {
8641
+ } else if (anyAnswerFlagGiven || (opts.land && !isTTY)) {
8642
+ // #481: a bare --land with no terminal lands what is already on disk — it never asks.
7971
8643
  // Fully non-interactive: whatever flags were given get applied; anything still missing
7972
8644
  // just stays missing (reported in "remaining"), never prompted for — half a prompt is worse
7973
8645
  // than none. `stack` is the one exception: it is a required key, not an optional row, so an
@@ -7982,7 +8654,11 @@ async function cmdAdopt(argv) {
7982
8654
  } else if (isTTY) {
7983
8655
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
7984
8656
  try {
7985
- answers = await adoptAskInteractive(rl, axesToAsk, cfg);
8657
+ const shapeWorkflows = io.listDir('.github/workflows').filter((f) => /\.ya?ml$/.test(f));
8658
+ answers = await adoptAskInteractive(rl, axesToAsk, cfg, (exposure, sofar) => {
8659
+ const v = adopt.exposureShapeVerdict(exposure, adoptShapeCtx(cfg, sofar.tier, extra.trunk, shapeWorkflows, io, extra.branches));
8660
+ return v.ok ? null : v.reason;
8661
+ });
7986
8662
  if (needsStack && opts.stack === undefined) {
7987
8663
  process.stdout.write('\nNo manifest recognised (package.json/composer.json/pyproject.toml/'
7988
8664
  + '.python-version) — the audit requires stack: as a literal key.\n');
@@ -7997,6 +8673,12 @@ async function cmdAdopt(argv) {
7997
8673
  } else {
7998
8674
  const hints = axesToAsk.map(adoptAxisFlagHint).join(' ');
7999
8675
  const stackHint = stackUnresolvable ? ' --stack "<text>"' : '';
8676
+ // #522: the human step goes FIRST — answering exposure none/self is a human's act, so the one
8677
+ // command that finishes the adoption leads, and the explanation follows it.
8678
+ if (axesToAsk.includes('exposure')) {
8679
+ warn('a human finishes this adoption — run at an interactive terminal: colab adopt (or, non-interactively:)');
8680
+ warn(` ${adopt.humanAdoptCommand(adoptAskedFlagPlaceholders(axesToAsk, stackUnresolvable))}`);
8681
+ }
8000
8682
  warn(`${axesToAsk.length} unanswered §9 row(s) (${axesToAsk.join(', ')}) — no TTY and no answer flags, so there is no way to ask. Re-run with: ${hints}${stackHint}`);
8001
8683
  return 1;
8002
8684
  }
@@ -8021,7 +8703,7 @@ async function cmdAdopt(argv) {
8021
8703
  // written, per "nothing partially written on refusal".
8022
8704
  if (answers.exposure) {
8023
8705
  const proposedExposure = answers.exposure.values.exposure;
8024
- const shapeCtx = adoptShapeCtx(cfg, answers.tier, trunk, workflows, io);
8706
+ const shapeCtx = adoptShapeCtx(cfg, answers.tier, trunk, workflows, io, extra.branches);
8025
8707
  const evidence = consumerEvidence.consumerEvidence(io, workflows);
8026
8708
  const currentExposure = axisAuthority.axisOfRecord(cfg).exposure;
8027
8709
  const verdict = adopt.gateVerdict({
@@ -8035,6 +8717,10 @@ async function cmdAdopt(argv) {
8035
8717
  reason: opts.reason || null,
8036
8718
  });
8037
8719
  if (!verdict.ok) {
8720
+ if (verdict.class === adopt.GATE_CLASS.HUMAN_GATED) {
8721
+ // #522: lead with the one command a human runs, every answer this run had filled in.
8722
+ warn(`a human finishes this adoption — run: ${adopt.humanAdoptCommand(adoptReplayFlags(opts, answers))}`);
8723
+ }
8038
8724
  warn(verdict.message);
8039
8725
  return verdict.exitCode;
8040
8726
  }
@@ -8109,6 +8795,10 @@ async function cmdAdopt(argv) {
8109
8795
  comment: `${adopt.provenanceComment('exposure', m)}${reasonSuffix}`,
8110
8796
  });
8111
8797
  }
8798
+ if (autonomyWrite) {
8799
+ entries.push({ key: 'autonomy', value: opts.autonomy, comment: adopt.provenanceComment('autonomy',
8800
+ { mode: 'flag', flags: ['--autonomy'], date: nowDate, colabHuman, answeredBy: opts.answeredBy || null }) });
8801
+ }
8112
8802
  // Fallback: exposure ends this run still unanswered (declined interactively, or simply not
8113
8803
  // among the axes that got an answer this run) and no `tier` already exists — derive one from
8114
8804
  // (production, deploy), using the EFFECTIVE values (this run's tier answer, if any, else what
@@ -8164,16 +8854,19 @@ async function cmdAdopt(argv) {
8164
8854
  warn('nothing to write — every requested row was already answered, or nothing was supplied to answer it.');
8165
8855
  const verify = opts.noVerify ? null : adoptVerify(repoAbs);
8166
8856
  const lf = local ? adoptLocalFinish(repoAbs, local, opts) : undefined;
8167
- if (opts.json) { print(JSON.stringify({ repo: repoAbs, ...report, verify, written: [], local: lf }, null, 2)); return lf && !lf.ok ? 1 : 0; }
8857
+ const land = opts.land ? adoptLand(repoAbs, landTrunk, ['.github/project.yml'], opts.answeredBy) : undefined;
8858
+ const rc = (lf && !lf.ok) || (land && !land.ok) ? 1 : 0;
8859
+ if (opts.json) { print(JSON.stringify({ repo: repoAbs, ...report, verify, written: [], local: lf, land }, null, 2)); return rc; }
8168
8860
  printAdoptReport(report, repoAbs, verify, lf);
8169
- return lf && !lf.ok ? 1 : 0;
8861
+ printAdoptLand(land);
8862
+ return rc;
8170
8863
  }
8171
8864
 
8172
8865
  const newText = adopt.renderDescriptor(rawTextBefore, entries);
8173
8866
  fs.mkdirSync(path.dirname(descriptorFile), { recursive: true });
8174
8867
  fs.writeFileSync(descriptorFile, newText);
8175
8868
 
8176
- const afterExtra = adoptGitExtras(repoAbs);
8869
+ const afterExtra = adoptGitExtras(repoAbs, opts);
8177
8870
  if (local) { afterExtra.trunk = local.trunk; afterExtra.trunkSource = 'local-integration'; }
8178
8871
  const after = adopt.detect(adoptIo(repoAbs), afterExtra);
8179
8872
  // #417: a NEW repo (no descriptor before this run, plain adopt) gets the thin-shell CLAUDE.md
@@ -8182,19 +8875,83 @@ async function cmdAdopt(argv) {
8182
8875
  const shell = local || rawTextBefore !== null ? null : adoptWriteShell(repoAbs, after);
8183
8876
  const verify = opts.noVerify ? null : adoptVerify(repoAbs);
8184
8877
  const lf = local ? adoptLocalFinish(repoAbs, local, opts) : undefined;
8878
+ // #481: --land commits exactly what THIS run wrote — the descriptor, plus the thin shell when
8879
+ // it was written now — never anything else in the working tree.
8880
+ const landPaths = ['.github/project.yml'];
8881
+ if (shell && shell.claude === 'written') landPaths.push(CLAUDE_FILE);
8882
+ if (shell && shell.agents === 'written') landPaths.push('AGENTS.md');
8883
+ const land = opts.land ? adoptLand(repoAbs, landTrunk, landPaths, opts.answeredBy) : undefined;
8884
+ const rc = (lf && !lf.ok) || (land && !land.ok) ? 1 : 0;
8185
8885
  if (opts.json) {
8186
- print(JSON.stringify({ repo: repoAbs, ...after, verify, written: entries.map((e) => ({ key: e.key, value: e.value })), ...(shell ? { shell } : {}), local: lf }, null, 2));
8187
- return lf && !lf.ok ? 1 : 0;
8886
+ print(JSON.stringify({ repo: repoAbs, ...after, verify, written: entries.map((e) => ({ key: e.key, value: e.value })), ...(shell ? { shell } : {}), local: lf, land }, null, 2));
8887
+ return rc;
8188
8888
  }
8189
8889
  for (const e of entries) print(`✓ wrote ${e.key}: ${fmtVal(e.value)}`);
8190
8890
  if (shell) {
8191
- if (shell.claude === 'written') print('✓ wrote CLAUDE.md — the thin shell: @AGENTS.md + the Conventions block (§9 step 5, #417)');
8891
+ if (shell.claude === 'written' && shell.fork) print('✓ wrote CLAUDE.md — the Conventions block alone: a fork with no upstream AGENTS.md gets no stub (§9 "A fork of an upstream", #449)');
8892
+ else if (shell.claude === 'written') print('✓ wrote CLAUDE.md — the thin shell: @AGENTS.md + the Conventions block (§9 step 5, #417)');
8192
8893
  else if (shell.claude === 'skipped') print(`· CLAUDE.md not written — ${shell.reason}`);
8193
8894
  if (shell.agents === 'written') print('✓ wrote AGENTS.md — a stub; the repo\'s own instructions go here');
8194
8895
  }
8195
8896
  print('');
8196
8897
  printAdoptReport(after, repoAbs, verify, lf);
8197
- return lf && !lf.ok ? 1 : 0;
8898
+ printAdoptLand(land);
8899
+ return rc;
8900
+ }
8901
+
8902
+ /**
8903
+ * #481 — `--land` preflight: is origin's trunk ahead of this checkout? Landing on a stale trunk
8904
+ * would either fail the push or need a merge, and adopt does neither on a human's behalf. Returns a
8905
+ * refusal message, or null. No origin remote, or no trunk there yet (a first push), is not behind.
8906
+ */
8907
+ function adoptLandBehind(repoAbs, trunk) {
8908
+ if (!git.git(['remote', 'get-url', 'origin'], repoAbs).ok) return null;
8909
+ const f = git.git(['fetch', 'origin', trunk], repoAbs);
8910
+ if (!f.ok) {
8911
+ const remoteHas = git.git(['ls-remote', '--exit-code', '--heads', 'origin', trunk], repoAbs);
8912
+ if (remoteHas.ok) return `--land could not fetch origin/${trunk} — refusing to land on a trunk it cannot see: ${f.stderr || f.stdout}`;
8913
+ return null; // origin has no trunk yet: the landing push creates it
8914
+ }
8915
+ const anc = git.git(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'], repoAbs);
8916
+ if (anc.ok) return null;
8917
+ return `--land refuses: origin/${trunk} has commits this checkout does not — pull ${trunk} first, then re-run`;
8918
+ }
8919
+
8920
+ /**
8921
+ * #481 — commit `paths` (only those) onto trunk and push it. Called only after landVerdict passed
8922
+ * (COLAB_HUMAN=1 + --answered-by, standing on trunk), so the pre-push guard's COLAB_HUMAN door is
8923
+ * the one this push walks through — the same env the human set. Nothing staged for these paths
8924
+ * (already committed) is not an error: it still pushes a trunk that is ahead of origin.
8925
+ */
8926
+ function adoptLand(repoAbs, trunk, paths, answeredBy) {
8927
+ const present = paths.filter((p) => fs.existsSync(path.join(repoAbs, p)));
8928
+ if (!present.length) return { ok: false, trunk, committed: [], sha: null, pushed: false, error: 'no descriptor on disk to land' };
8929
+ const add = git.git(['add', '--', ...present], repoAbs);
8930
+ if (!add.ok) return { ok: false, trunk, committed: [], sha: null, pushed: false, error: `git add failed: ${add.stderr || add.stdout}` };
8931
+ const staged = git.git(['diff', '--cached', '--name-only', '--', ...present], repoAbs);
8932
+ const committed = staged.ok && staged.stdout ? staged.stdout.split('\n').filter(Boolean) : [];
8933
+ if (committed.length) {
8934
+ const c = git.git(['commit', '--only', '-m', adopt.landCommitMessage({ answeredBy, paths: committed }), '--', ...committed], repoAbs);
8935
+ if (!c.ok) return { ok: false, trunk, committed: [], sha: null, pushed: false, error: `git commit failed: ${c.stderr || c.stdout}` };
8936
+ }
8937
+ const head = git.git(['rev-parse', 'HEAD'], repoAbs);
8938
+ const sha = head.ok ? head.stdout : null;
8939
+ if (!git.git(['remote', 'get-url', 'origin'], repoAbs).ok) {
8940
+ return { ok: true, trunk, committed, sha, pushed: false, note: 'no origin remote — committed locally; the first push of trunk carries it' };
8941
+ }
8942
+ const p = git.git(['push', 'origin', `HEAD:refs/heads/${trunk}`], repoAbs);
8943
+ if (!p.ok) return { ok: false, trunk, committed, sha, pushed: false, error: `committed ${shortSha(sha)} on ${trunk}, but the push failed: ${p.stderr || p.stdout}` };
8944
+ return { ok: true, trunk, committed, sha, pushed: true };
8945
+ }
8946
+
8947
+ function printAdoptLand(land) {
8948
+ if (!land) return;
8949
+ print('');
8950
+ if (!land.ok) { print(`✗ land: ${land.error}`); return; }
8951
+ const what = land.committed.length ? `committed ${land.committed.join(', ')} as ${shortSha(land.sha)}` : `nothing new to commit (trunk at ${shortSha(land.sha)})`;
8952
+ print(`✓ land: ${what} on ${land.trunk}${land.pushed ? ` — pushed to origin/${land.trunk}` : ''}`);
8953
+ if (land.note) print(` ${land.note}`);
8954
+ print(' The follow-up branch (CI, guards, docs) is judged by this descriptor — ship it through the normal lane.');
8198
8955
  }
8199
8956
 
8200
8957
  /**
@@ -8224,6 +8981,14 @@ function adoptWriteShell(repoAbs, after) {
8224
8981
  const version = handbookVersion(root);
8225
8982
  const atTag = version === 'v0' ? null : stamp.gitIn(root, ['show', `${version}:templates/repo-CLAUDE-block.md`]);
8226
8983
  const blockText = atTag && atTag.ok && atTag.out ? atTag.out : fs.readFileSync(blockFile, 'utf8');
8984
+ // #449: on a fork, every file adopt creates is one the upstream may add later — a merge conflict
8985
+ // forever after. So no AGENTS.md stub there: with the upstream's own AGENTS.md the shell imports
8986
+ // it, without one CLAUDE.md is the block alone.
8987
+ const forkNoAgents = !!(after && after.fork) && !fs.existsSync(agentsAbs);
8988
+ if (forkNoAgents) {
8989
+ fs.writeFileSync(claudeAbs, adopt.renderClaudeShell(blockText, { version, trunk, tier, importAgents: false }));
8990
+ return { claude: 'written', agents: null, fork: true };
8991
+ }
8227
8992
  fs.writeFileSync(claudeAbs, adopt.renderClaudeShell(blockText, { version, trunk, tier }));
8228
8993
  let agents = 'exists';
8229
8994
  if (!fs.existsSync(agentsAbs)) { fs.writeFileSync(agentsAbs, adopt.renderAgentsStub()); agents = 'written'; }
@@ -9017,6 +9782,19 @@ function newMigrations(mainRoot, trunk, branch) {
9017
9782
  return r.stdout.split('\n').filter(Boolean).filter((f) => migrationPaths.isMigrationPath(f, declared));
9018
9783
  }
9019
9784
 
9785
+ /**
9786
+ * #508 — the content id (migration-grant.js migrationContentId) of `paths` — the branch's migration
9787
+ * files, newMigrations' list — as they stand at `sha`: one `git ls-tree` for their blob ids, a path
9788
+ * the commit no longer has counting as deleted. null when the tree cannot be read or there is
9789
+ * nothing to bind; null never matches a recorded id, so an unreadable tree fails the binding closed.
9790
+ */
9791
+ function migrationContentAt(repoAbs, paths, sha) {
9792
+ if (!sha || !Array.isArray(paths) || paths.length === 0) return null;
9793
+ const r = git.git(['ls-tree', '-z', sha, '--', ...paths], repoAbs);
9794
+ if (!r.ok) return null;
9795
+ return migrationGrant.migrationContentId(migrationGrant.migrationEntriesFromLsTree(r.stdout, paths));
9796
+ }
9797
+
9020
9798
  /**
9021
9799
  * The `no new migrations` row, whole (#98, #401) — the ONE function every ship path calls:
9022
9800
  * `ship --dry`, a real or auto-trunk `ship` (both cmdShip), and `ship --dry --json` (cmdShipDryJson,
@@ -9034,6 +9812,8 @@ function newMigrations(mainRoot, trunk, branch) {
9034
9812
  * evaluateShipSet ctx: the policy (P) from project.yml AT THE TARGET TIP — what the branch merges
9035
9813
  * into, not a working file the branch could have edited; the HEAD — the branch's remote head (what
9036
9814
  * CI ran), which must equal the local ref (what the squash takes), or no reviewer grant can bind;
9815
+ * the migration content id at that HEAD (#508), which a content-bound grant matches instead of
9816
+ * the reviewed HEAD — so the merge-of-trunk sync ship itself demands does not void the grant;
9037
9817
  * and R lazily — every job of every run at that HEAD, read only once some issue clears P+M+HEAD.
9038
9818
  */
9039
9819
  function shipMigrationGate(repoAbs, gh, target, branch, issues) {
@@ -9047,7 +9827,7 @@ function shipMigrationGate(repoAbs, gh, target, branch, issues) {
9047
9827
  } else {
9048
9828
  const records = {};
9049
9829
  for (const n of issues) records[n] = git.ghIssueView(repoAbs, n, ['state', 'labels', 'comments']);
9050
- ctx = shipMigrationCtx(repoAbs, gh, target, branch);
9830
+ ctx = shipMigrationCtx(repoAbs, gh, target, branch, migrations);
9051
9831
  grants = migrationGrant.evaluateShipSet(issues, records, branch, labels.MIGRATION_GRANT_LABEL, ctx);
9052
9832
  }
9053
9833
  return { migrations, ok: grants.ok, ...migDetail(migrations, grants, target, branch, ctx) };
@@ -9055,7 +9835,7 @@ function shipMigrationGate(repoAbs, gh, target, branch, issues) {
9055
9835
 
9056
9836
  /** P, HEAD and the R thunk for shipMigrationGate. The thunk memoises its one verdict on the ctx
9057
9837
  * (`roundtripResult`) so the payload can report what R saw without a second read. */
9058
- function shipMigrationCtx(repoAbs, gh, target, branch) {
9838
+ function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
9059
9839
  const policy = migrationGrant.parseGrantPolicy(projectDocAt(repoAbs, target)).policy;
9060
9840
  const remote = git.remoteInfo(repoAbs).name || 'origin';
9061
9841
  const ls = git.git(['ls-remote', remote, `refs/heads/${branch}`], repoAbs);
@@ -9067,7 +9847,9 @@ function shipMigrationCtx(repoAbs, gh, target, branch) {
9067
9847
  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`;
9068
9848
  else headSha = remoteSha;
9069
9849
  const trust = trustAt(repoAbs, target);
9070
- const ctx = { policy, headSha, headNote, roundtripResult: null, trust,
9850
+ // #508: what the branch's migration files ARE at the shipped head, for a content-bound grant.
9851
+ const contentId = headSha ? migrationContentAt(repoAbs, migrations, headSha) : null;
9852
+ const ctx = { policy, headSha, contentId, headNote, roundtripResult: null, trust,
9071
9853
  labelActors: (n) => git.ghIssueLabelActors(repoAbs, n, labels.MIGRATION_GRANT_LABEL) };
9072
9854
  ctx.roundtrip = () => {
9073
9855
  const d = git.git(['diff', '--name-only', `${target}...${branch}`], repoAbs);
@@ -9101,16 +9883,17 @@ function migDetail(migrations, grants, target, branch, ctx) {
9101
9883
  branch, files: [...migrations],
9102
9884
  policy: ctx ? ctx.policy : null,
9103
9885
  headSha: ctx ? ctx.headSha : null,
9886
+ contentId: ctx ? ctx.contentId || null : null,
9104
9887
  // #407: the human list as read from the TARGET — null when undeclared (association class).
9105
9888
  trustHumans: ctx && ctx.trust && ctx.trust.declared ? [...ctx.trust.humans] : null,
9106
9889
  roundtrip: ctx && ctx.roundtripResult ? { ok: ctx.roundtripResult.ok, reason: ctx.roundtripResult.reason } : null,
9107
9890
  granted: grants.granted.map((g) => ({ issue: g.issue, role: g.role || 'human', by: g.by, at: g.at,
9108
- ...(g.role === 'reviewer' ? { reviewer: g.reviewer, head: g.head } : {}) })),
9891
+ ...(g.role === 'reviewer' ? { reviewer: g.reviewer, head: g.head, via: g.via || 'head', migrations: g.migrations || null } : {}) })),
9109
9892
  missing: grants.missing.map((m) => ({ issue: m.issue, failed: m.failed || null,
9110
9893
  reason: m.failed === 'head' && ctx && ctx.headNote ? `${m.reason} (${ctx.headNote})` : m.reason })),
9111
9894
  };
9112
9895
  if (grants.ok) {
9113
- const by = grants.granted.map((g) => (g.role === 'reviewer' ? `#${g.issue} (reviewer ${g.reviewer} @ ${String(g.head).slice(0, 7)}, CI round-trip passed)` : '#' + g.issue)).join(' ');
9896
+ 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(' ');
9114
9897
  const roles = [...new Set(grants.granted.map((g) => g.role || 'human'))].join('+');
9115
9898
  return { text: `${migrations.length} present, exempted by a ${roles} grant on ${by} for branch "${branch}" — ${files}`, payload };
9116
9899
  }
@@ -9206,7 +9989,11 @@ function ciGrantTrailerLine(grantVerdict, branch, trunk) {
9206
9989
  if (!grantVerdict || !grantVerdict.ok || !grantVerdict.granted.length) return null;
9207
9990
  const g = grantVerdict.granted[0]; // redSha/evidenceSha are identical across the whole granted set (evaluateShipSet)
9208
9991
  const issues = grantVerdict.granted.map((x) => '#' + x.issue).join(' ');
9209
- return `CI-Grant: ${issues} branch ${branch} over-red ${trunk}@${shortSha(g.redSha)} evidence ${shortSha(g.evidenceSha)}`;
9992
+ // #504: a reviewer grant appends who reviewed it; the `over-red <trunk>@<sha>` part the anti-stacking
9993
+ // scan (ci-cure.js priorRedShaFromMessage) reads is unchanged.
9994
+ const rv = grantVerdict.granted.filter((x) => x.role && x.role !== 'human');
9995
+ const via = rv.length ? ` via ${rv[0].role} ${[...new Set(rv.map((x) => x.reviewer))].join(',')}` : '';
9996
+ return `CI-Grant: ${issues} branch ${branch} over-red ${trunk}@${shortSha(g.redSha)} evidence ${shortSha(g.evidenceSha)}${via}`;
9210
9997
  }
9211
9998
 
9212
9999
  /**
@@ -9221,27 +10008,40 @@ function ciGrantTrailerLine(grantVerdict, branch, trunk) {
9221
10008
  * line without touching the scan.
9222
10009
  *
9223
10010
  * A cure admitted through the #321 workflow carve-out appends ` via workflow-carve-out jobs <a,b>`.
9224
- * That suffix is not decoration: anti-stacking permits exactly ONE exemption per continuous red
10011
+ * That suffix is not decoration: anti-stacking permits ONE exemption per continuous red (more only on progress, #477)
9225
10012
  * episode, so a later reader has to be able to tell WHICH door spent it — and a cure that went
9226
10013
  * through the widened door on a branch editing the CI config is a materially different fact from an
9227
10014
  * ordinary one. The commit is the only artifact that still says so after the runs age out.
9228
10015
  */
9229
10016
  function ciCureTrailerLine(cureVerdict, branch, trunk) {
9230
10017
  if (!cureVerdict || !cureVerdict.ok) return null;
9231
- const via = cureVerdict.carveOut
10018
+ const via = (cureVerdict.carveOut
9232
10019
  ? ` via workflow-carve-out jobs ${cureVerdict.carveOut.jobs.map((j) => j.name).join(',')}`
9233
- : '';
9234
- return `CI-Cure: branch ${branch} over-red ${trunk}@${shortSha(cureVerdict.redSha)} evidence ${shortSha(cureVerdict.evidenceSha)}${via}`;
9235
- }
9236
-
9237
- const HELP_SHIP = `colab ship [--repo <path>] [--worktree <name> | --branch <br> | --direct] [--message "<msg>"] [--refs <N[,M]>] [--keep-worktree] [--delete-branch | --keep-branch] [--adopt] [--session <id>] [--session-name <s>] [--dry] [--json]
10020
+ : '') + (cureVerdict.dryRun ? ` via dry-run jobs ${cureVerdict.dryRun.jobs.join(',')}` : '')
10021
+ + (cureVerdict.dispatch ? ` via dispatch jobs ${cureVerdict.dispatch.jobs.join(',')}` : ''); // #510
10022
+ // #475/#476: a cure that changed a manifest under an admission says which, for the same reason.
10023
+ const adm = cureVerdict.admitted || {};
10024
+ const manifest = [adm.scripts ? 'add-only-scripts' : null, adm.pins ? 'pin-only-requirements' : null].filter(Boolean);
10025
+ const admittedSuffix = manifest.length ? ` admitted ${manifest.join(',')}` : '';
10026
+ // #477: a cure that spent condition 3 by progress past a prior exemption says so, and which jobs
10027
+ // healed — the next cure on this red compares against THIS line's over-red sha.
10028
+ const progressSuffix = cureVerdict.progress
10029
+ ? ` after-progress healed ${cureVerdict.progress.healed.join(',')}` : '';
10030
+ return `CI-Cure: branch ${branch} over-red ${trunk}@${shortSha(cureVerdict.redSha)} evidence ${shortSha(cureVerdict.evidenceSha)}${via}${admittedSuffix}${progressSuffix}`;
10031
+ }
10032
+
10033
+ 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]
9238
10034
  colab ship --batch <b1,b2[,b3]> [--repo <path>] [--keep-worktree] [--delete-branch | --keep-branch] [--session <id>] [--session-name <s>] [--dry]
9239
10035
 
9240
10036
  The ONE sanctioned door for code-wrap Phase B: squash-merge a session branch into the BASE IT WAS
9241
10037
  CUT FROM — trunk for an ordinary session, or the declared integration line recorded on its worktree
9242
10038
  (project.yml \`integration:\`). Autonomy is granted by the repo's .github/project.yml
9243
10039
  (\`autonomy: auto-trunk\`) — NOT by any flag. Without that grant, ship refuses and a human must run
9244
- Phase B — unless the change is DOCS-ONLY, computed from git (#345, below). ship NEVER touches main (when trunk≠main), NEVER tags, NEVER promotes.
10040
+ Phase B — unless the change is DOCS-ONLY, computed from git (#345, below). That human runs ship
10041
+ too, through the HUMAN DOOR (#525): at an interactive terminal (outside an agent shell) ship asks
10042
+ them to confirm; non-interactively, COLAB_HUMAN=1 plus --answered-by <name>. Every other
10043
+ precondition still applies, and the 🚢 comment records that the human door opened the gate.
10044
+ ship NEVER touches main (when trunk≠main), NEVER tags, NEVER promotes.
9245
10045
 
9246
10046
  Base and target are ONE decision. A branch cut from a long-lived line and shipped into trunk would
9247
10047
  drag the entire line in behind it, as a single squash commit that reads like a small change — so
@@ -9251,6 +10051,8 @@ promotes is an integration event of the same weight as a promotion, and stays hu
9251
10051
 
9252
10052
  Sequence (each step gated; any failure aborts before the push — the target is never half-shipped):
9253
10053
  a. autonomy gate repo must grant auto-trunk (no --force override) — or the diff is docs-only (#345)
10054
+ — or a person runs ship through the human door (#525): a confirmed interactive
10055
+ terminal, or COLAB_HUMAN=1 + --answered-by <name>. An agent shell is no terminal.
9254
10056
  b. preconditions target CI alive+green (UNLESS the branch proves the CURE RULE, #281 — no
9255
10057
  human step needed — OR every issue the branch carries holds a valid
9256
10058
  \`colab ci-grant\` over trunk's CURRENT red sha, #105 — see below) · no new
@@ -9362,7 +10164,9 @@ makes today); (2) the branch's own CI is green AT ITS OWN CURRENT HEAD, measured
9362
10164
  and (2b, #297) every job RED on trunk at the red sha exists in the branch's runs at that head,
9363
10165
  completed and \`success\` (a green run in which the failing check never ran proves nothing);
9364
10166
  (3) the same anti-stacking guard ci-grant uses holds (no prior grant OR cure merged while trunk has
9365
- stayed continuously red since); (4) the branch diff does not touch \`.github/workflows/**\` (a branch
10167
+ stayed continuously red since) — UNLESS trunk's red-job set now is a STRICT subset of the set at the
10168
+ red sha the prior exemption's trailer names (#477: progress, so two failures healed by two fixes need
10169
+ no human; an unchanged or grown set still refuses); (4) the branch diff does not touch \`.github/workflows/**\` (a branch
9366
10170
  may not self-certify a change to the CI configuration grading it; renames count) — UNLESS it passes
9367
10171
  the #321 CARVE-OUT below; (5, #297) the branch diff does not change the \`scripts\` block of any
9368
10172
  \`package.json\` — CI templates read that block to decide which checks run, so it is part of the
@@ -9383,7 +10187,7 @@ nothing — this is the sub-test that catches a fast exit, because GitHub report
9383
10187
  were all skipped as \`conclusion: success\`); (4c) each of those jobs cost at least the wall time its
9384
10188
  failure did on trunk. Anything unmeasurable refuses, exactly as before. A carve-out cure names the
9385
10189
  door in its \`CI-Cure:\` trailer and in \`--dry --json\`'s \`ciCure.via\`, because anti-stacking permits
9386
- only ONE exemption per continuous red and a later reader must be able to tell which door spent it.
10190
+ only ONE exemption per continuous red (more only while its red-job set shrinks, #477) and a later reader must be able to tell which door spent it.
9387
10191
  Its own honest limit: it proves the red jobs still ran the steps they ran and still cost the time —
9388
10192
  never what those steps ASSERTED. Known false refusal: a trunk job that failed by TIMEOUT ran longer
9389
10193
  than any healthy run, so (4c) refuses the genuine repair; take the ordinary ci-grant door there.
@@ -9464,7 +10268,9 @@ It never waits: each call reads the remote, takes ONE step and exits —
9464
10268
  trunk CI red (the cure/grant doors apply per member, never to a batch), fewer than two members
9465
10269
  can join, or the combined run is red — classify it: red:infra → the printed \`gh run rerun\`,
9466
10270
  once; red:finding, or red again after that one re-run → serial
9467
- 1 refused (a broken checkout, an unreadable remote)
10271
+ 1 refused (a broken checkout, an unreadable remote) — or the land push was refused while trunk did
10272
+ NOT move (a local pre-push hook, a remote rejection): the push's own output is echoed, and
10273
+ re-running hits the same refusal until its cause is fixed (#509)
9468
10274
  One batch per base: a batch at this base carrying OTHER members is waited on (exit 3) while its run
9469
10275
  is pending or green, but a declined one — its combined run red — is deleted and the batch you asked
9470
10276
  for is built in its place, so the survivors of a decline can batch without landing serially first (#391).
@@ -9512,7 +10318,9 @@ Options:
9512
10318
  warning). --dry prints "Machine trailer: …" saying which way it will go.
9513
10319
  --refs <N[,M]> reference these claimed issues (Refs #N) instead of closing them — for a
9514
10320
  long-lived memory/tracking issue the branch touched but did not complete.
9515
- Comma-separated; each must be a claimed issue on the branch. An issue carrying
10321
+ Comma-separated, and repeatable: --refs A --refs B is --refs A,B (#479 —
10322
+ every other value flag to ship refuses a repeat). Each must be a claimed
10323
+ issue on the branch. An issue carrying
9516
10324
  the "tracking" label is treated this way automatically, no flag needed. The
9517
10325
  claim is still released either way — only Closes→Refs changes.
9518
10326
  #385: a --refs'd issue whose body still has an unticked "- [ ]" box (under
@@ -9555,7 +10363,8 @@ Options:
9555
10363
  instead — an unattended caller must NOT read it as a no-op. "pr-pending"
9556
10364
  (#350) means a real run would open/reuse a PR and PAUSE (exit 3) — additive
9557
10365
  keys \`coreReview\` ({ active, verdict, inertReason, codeownersPath, corePaths,
9558
- headSha, pr, approval }) and \`machineTrailer\` ("Machine: <label>") say why.
10366
+ ignoredOwners (#483: a fork's inherited foreign-org teams), headSha, pr,
10367
+ approval }) and \`machineTrailer\` ("Machine: <label>") say why.
9559
10368
  \`machineTrailer\` is null whenever the trailer is omitted (#367), and
9560
10369
  \`machineTrailerDecision\` ({ include, reason, visibility, room, failClosed },
9561
10370
  null on evidence-close) says which way the squash will go and why.
@@ -9905,23 +10714,91 @@ function descriptorHolds(doc) {
9905
10714
  * caller can build the --dry --json `ciGrant`/`ciCure` payloads from the SAME verdicts the prose
9906
10715
  * detail string was built from — see ciGrantPayload/ciCurePayload, below.
9907
10716
  */
9908
- function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
10717
+ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk, branch = null) {
9909
10718
  const name = `${target === trunk ? 'trunk' : 'line'} CI green`;
9910
- if (!gh) return { name, ok: false, class: SELF_CLEARING, detail: `gh not usable (${ghUnusableWhy(repoAbs)}) — cannot confirm CI`, grantVerdict: null, cureVerdict: null };
9911
- let run = git.ghRunForSha(repoAbs, target);
10719
+ const r = readCiVerdict(repoAbs, gh, target, trunk);
10720
+ const nw = noWorkflowTrunkDoor(repoAbs, r, target, trunk, branch);
10721
+ if (nw) return { name, ...nw, grantVerdict: null, cureVerdict: null };
10722
+ if (r.final) return { name, ...r.verdict, grantVerdict: null, cureVerdict: null };
10723
+ return applyRedTrunkExemptions({ name, ...r.verdict }, target, trunk, r.run.sha, grantThunk, cureThunk);
10724
+ }
10725
+
10726
+ /**
10727
+ * #482: a trunk with NO repo-owned workflow file at its head sha (a freshly adopted repo whose
10728
+ * adoption branch is what adds CI) can never draw a run, so its `none` is not a gap in CI — there is
10729
+ * no CI there to be red. It reads `none` and gets Branch CI's `none`-that-cannot-arrive treatment
10730
+ * (CONVENTIONS.md §4): the candidate's OWN run at its remote head decides. Green there → the row
10731
+ * passes; anything else → the ordinary refusal stands, with the reason appended.
10732
+ *
10733
+ * Fails closed: only a trunk sha present locally whose tree demonstrably has no
10734
+ * `.github/workflows/*.yml|yaml` qualifies. A trunk that HAS workflows but no run at its sha is a
10735
+ * real gap (CI not wired, or never started) and still blocks exactly as before. Runs ahead of the
10736
+ * #413 grace window too: a run that can never exist is not worth waiting ten minutes for. Returns null when
10737
+ * the door does not apply, or a `{ok, class, detail}` verdict when it does.
10738
+ */
10739
+ function noWorkflowTrunkDoor(repoAbs, r, target, trunk, branch) {
10740
+ if (target !== trunk || !branch || !r.run || r.run.status !== 'none' || !r.run.sha || r.verdict.ok) return null;
10741
+ if (trunkWorkflowFiles(repoAbs, r.run.sha) !== 0) return null;
10742
+ const at = `${trunk}@${shortSha(r.run.sha)}`;
10743
+ const own = git.ghRunForSha(repoAbs, branch);
10744
+ // Branch not on the remote, or its runs unreadable: nothing to decide with — the prior verdict stands.
10745
+ if (!own) return null;
10746
+ const ownAt = own.sha ? `${branch}@${shortSha(own.sha)}` : branch;
10747
+ if (own && own.status === 'completed' && own.conclusion === 'success') {
10748
+ const n = own.runCount == null ? 1 : own.runCount;
10749
+ return { ok: true, class: null,
10750
+ detail: `none — ${at} has no repo-owned workflow, so nothing there can be red (#482); the branch's own run decides: ${n} run${n === 1 ? '' : 's'} at ${ownAt}: ${n === 1 ? 'success' : 'all success'}${excludedRunsNote(r.run)}` };
10751
+ }
10752
+ const why = own.status === 'none' ? 'has no run' : `is status=${own.status} conclusion=${own.conclusion || 'none'}`;
10753
+ return { ok: false, class: own.status !== 'completed' && own.status !== 'none' ? SELF_CLEARING : HUMAN_GATED,
10754
+ detail: `none — ${at} has no repo-owned workflow (#482), so the branch's own run decides, and ${ownAt} ${why}${excludedRunsNote(r.run)}` };
10755
+ }
10756
+
10757
+ /** Number of workflow files in `.github/workflows` at `sha`, or null when the tree cannot be read. */
10758
+ function trunkWorkflowFiles(repoAbs, sha) {
10759
+ if (!git.git(['cat-file', '-e', `${sha}^{commit}`], repoAbs).ok) return null;
10760
+ const ls = git.git(['ls-tree', '--name-only', `${sha}:.github/workflows`], repoAbs);
10761
+ if (!ls.ok) {
10762
+ // No such directory is a real zero; any other failure is unknown (fail closed).
10763
+ const dir = git.git(['ls-tree', '--name-only', sha, '.github/workflows'], repoAbs);
10764
+ return dir.ok && dir.stdout.trim() === '' ? 0 : null;
10765
+ }
10766
+ return ls.stdout.split('\n').map((x) => x.trim()).filter((f) => /\.ya?ml$/.test(f)).length;
10767
+ }
10768
+
10769
+ /**
10770
+ * The CI read and its classification, BEFORE any exemption door (#463) — the one function both
10771
+ * `shipCiCheck` above and `colab trunk-ci` (cmdTrunkCi) call, so code-triage's "is trunk red?" and
10772
+ * ship's "trunk CI green" precondition can no longer disagree about a sha. They did: triage read
10773
+ * "red only when every run completed and none succeeded" in its own `gh run list` filter, so a sha
10774
+ * with one green workflow beside a red one read GREEN to triage while ship parked every candidate.
10775
+ *
10776
+ * Returns `{ run, verdict, final }`. `verdict` is `{ok, class, detail}`; `run` is the summarized
10777
+ * run (null when gh is unusable or the read failed). `final` is true when no exemption door applies
10778
+ * (green, self-clearing, unreadable, or a batch substitute answered) — the caller returns `verdict`
10779
+ * as is; false means a HUMAN_GATED verdict that `shipCiCheck` still offers to the cure rule and the
10780
+ * ci-grant. `trunk-ci` deliberately reports the pre-exemption verdict: an exemption lets ONE
10781
+ * branch past a red trunk, it does not make the trunk green, and the red still needs an owner.
10782
+ */
10783
+ function readCiVerdict(repoAbs, gh, target, trunk) {
10784
+ if (!gh) return { run: null, final: true, verdict: { ok: false, class: SELF_CLEARING, detail: `gh not usable (${ghUnusableWhy(repoAbs)}) — cannot confirm CI` } };
10785
+ // #503: only runs that VERIFY the code count — a post-CI release/deploy run at the same sha is set
10786
+ // aside and named, never a red and never a reason to wait (tools/lib/verify-runs.js).
10787
+ const readOpts = { verifying: verifyRuns.parsePolicy(projectDoc(repoAbs)) };
10788
+ let run = git.ghRunForSha(repoAbs, target, undefined, undefined, readOpts);
9912
10789
  let via = target;
9913
10790
  if (run && run.status === 'none' && target !== trunk) {
9914
- run = git.ghRunForSha(repoAbs, trunk);
10791
+ run = git.ghRunForSha(repoAbs, trunk, undefined, undefined, readOpts);
9915
10792
  via = `${trunk} (line "${target}" has no runs — ungated, advisory)`;
9916
10793
  }
9917
- if (!run) return { name, ok: false, class: SELF_CLEARING, detail: 'gh run list failed', grantVerdict: null, cureVerdict: null };
10794
+ if (!run) return { run: null, final: true, verdict: { ok: false, class: SELF_CLEARING, detail: 'gh run list failed' } };
9918
10795
  // #413: an empty BRANCH-filtered read of trunk's head is a second opinion away from `none`. It was
9919
10796
  // measured coming back empty for a trunk sha whose green run existed, then clearing a minute later
9920
10797
  // — and `none` classes HUMAN_GATED, so a transient read parked a ready candidate for a human.
9921
10798
  // Re-read the same sha by commit (the read `release finalize` already trusts, #339) before
9922
10799
  // believing it. A failed re-read changes nothing: the branch read's `none` stands.
9923
10800
  if (run.status === 'none' && target === trunk) {
9924
- const byCommit = git.ghRunForCommitAnyRef(repoAbs, run.sha);
10801
+ const byCommit = git.ghRunForCommitAnyRef(repoAbs, run.sha, undefined, readOpts);
9925
10802
  if (byCommit && byCommit.status !== 'none') {
9926
10803
  run = byCommit;
9927
10804
  via = `${trunk} (by commit — the branch-filtered read was empty)`;
@@ -9936,7 +10813,7 @@ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
9936
10813
  const fresh = ciVerdict.emptyReadVerdict(git.commitTimeMs(repoAbs, run.sha));
9937
10814
  if (fresh.fresh) {
9938
10815
  verdict = { ok: false, class: SELF_CLEARING,
9939
- detail: `no run yet for ${at} — committed ${fresh.minutes.toFixed(1)}m ago, inside the ${ciVerdict.EMPTY_READ_GRACE_MINUTES}m grace; retry later` };
10816
+ detail: `no run yet for ${at} — committed ${fresh.minutes.toFixed(1)}m ago, inside the ${ciVerdict.EMPTY_READ_GRACE_MINUTES}m grace; retry later${excludedRunsNote(run)}${verifyRuns.setAsideNote(run.setAside)}` };
9940
10817
  }
9941
10818
  }
9942
10819
  // #373: trunk's own run not there yet or still in flight (never a finished red) — a batch that landed
@@ -9944,10 +10821,43 @@ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
9944
10821
  // Inert (no gh call) unless project.yml declares ship-batch > 1.
9945
10822
  if (!verdict.ok && target === trunk && (run.status === 'none' || verdict.class === SELF_CLEARING)) {
9946
10823
  const sub = shipBatchTrunkSubstitute(repoAbs, trunk, run.sha);
9947
- if (sub) return { name, ...sub, grantVerdict: null, cureVerdict: null };
10824
+ if (sub) return { run, final: true, verdict: sub };
10825
+ }
10826
+ if (verdict.ok && target === trunk) verdict = treeGreenVerdict(repoAbs, run, verdict);
10827
+ return { run, verdict, final: verdict.ok || verdict.class !== HUMAN_GATED };
10828
+ }
10829
+
10830
+ /**
10831
+ * #493: a green trunk read whose suite was SKIPPED because the CI guard found a green run of the
10832
+ * same workflow at an identical tree — name the run it relied on. The run's `success` is already
10833
+ * the verdict (same as #418's sha skip); the citation is the audit pointer, so a citation that
10834
+ * cannot be read leaves the verdict green and says so. One thing turns it red: the cited head is
10835
+ * local and its tree provably differs from trunk's — the skip relied on a run of a DIFFERENT
10836
+ * tree, so trunk is untested (HUMAN_GATED, a person looks). An ordinary green run costs one
10837
+ * check-runs read and keeps its detail byte-identical.
10838
+ */
10839
+ function treeGreenVerdict(repoAbs, run, verdict) {
10840
+ const checks = git.ghCommitCheckRuns(repoAbs, run.sha);
10841
+ const ids = treeGreen.treeSkipCheckRuns(checks);
10842
+ if (!ids || !ids.length) return verdict;
10843
+ const cites = [];
10844
+ let unreadable = 0;
10845
+ const treeOf = (sha) => {
10846
+ const r = git.git(['rev-parse', '--verify', '--quiet', `${sha}^{tree}`], repoAbs);
10847
+ return r.ok ? r.stdout.trim() : null;
10848
+ };
10849
+ const ours = treeOf(run.sha);
10850
+ for (const id of ids) {
10851
+ const cite = treeGreen.parseCitation(git.ghCheckRunAnnotations(repoAbs, id));
10852
+ if (!cite) { unreadable++; continue; }
10853
+ const theirs = treeOf(cite.head);
10854
+ if (ours && theirs && ours !== theirs) {
10855
+ return { ok: false, class: HUMAN_GATED,
10856
+ detail: `${verdict.detail} — but the suite was SKIPPED on a tree-already-green citation (#493) of ${cite.url} (${cite.branch}@${shortSha(cite.head)}), whose tree ${theirs.slice(0, 12)} differs from trunk's ${ours.slice(0, 12)}: trunk is untested at this sha — re-run its CI, and report the guard` };
10857
+ }
10858
+ cites.push({ ...cite, proof: ours && theirs ? 'verified' : 'unverified' });
9948
10859
  }
9949
- if (verdict.ok || verdict.class !== HUMAN_GATED) return { name, ...verdict, grantVerdict: null, cureVerdict: null };
9950
- return applyRedTrunkExemptions({ name, ...verdict }, target, trunk, run.sha, grantThunk, cureThunk);
10860
+ return { ...verdict, detail: verdict.detail + treeGreen.citationNote(cites, unreadable), treeGreen: cites.map((c) => c.url) };
9951
10861
  }
9952
10862
 
9953
10863
  /**
@@ -9973,6 +10883,35 @@ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
9973
10883
  * the detail string still reads sensibly rather than "undefined runs".
9974
10884
  */
9975
10885
  function classifyCiRun(repoAbs, run, at) {
10886
+ const v = classifyCiRunRaw(repoAbs, run, at);
10887
+ return { ...v, detail: v.detail + excludedRunsNote(run) + supersededRunsNote(run) + verifyRuns.setAsideNote(run && run.setAside) };
10888
+ }
10889
+
10890
+ /**
10891
+ * #461: earlier runs of the same workflow at this sha that a newer run of it superseded — set aside
10892
+ * by git.summarizeRunsForCommit before the verdict, and named here so the reader sees what the
10893
+ * verdict did not judge. '' when none.
10894
+ */
10895
+ function supersededRunsNote(run) {
10896
+ const sup = run && Array.isArray(run.superseded) ? run.superseded : [];
10897
+ if (!sup.length) return '';
10898
+ const names = sup.map((x) => `${x.workflowName || 'unnamed'} (${x.conclusion || x.status || '?'}${x.databaseId ? `, run ${x.databaseId}` : ''})`);
10899
+ return ` — set aside ${sup.length} superseded run${sup.length === 1 ? '' : 's'} (a newer run of the same workflow decides, #461): ${names.join(', ')}`;
10900
+ }
10901
+
10902
+ /**
10903
+ * #451: the runs a verdict did NOT count, named in its detail — runs from workflows the repo does
10904
+ * not own (`event: dynamic`, e.g. Dependabot Updates) are dropped by git.summarizeRunsForCommit
10905
+ * before the verdict is computed, and a reader must be able to see what was dropped. '' when none.
10906
+ */
10907
+ function excludedRunsNote(run) {
10908
+ const ex = run && Array.isArray(run.excluded) ? run.excluded : [];
10909
+ if (!ex.length) return '';
10910
+ const names = ex.map((x) => `${x.workflowName || 'unnamed'} (${x.conclusion || x.status || '?'}${x.databaseId ? `, run ${x.databaseId}` : ''})`);
10911
+ return ` — excluded ${ex.length} run${ex.length === 1 ? '' : 's'} from workflows this repo does not own (event: dynamic, #451): ${names.join(', ')}`;
10912
+ }
10913
+
10914
+ function classifyCiRunRaw(repoAbs, run, at) {
9976
10915
  if (run.status === 'completed') {
9977
10916
  if (run.conclusion === 'success') {
9978
10917
  const n = run.runCount == null ? 1 : run.runCount;
@@ -10156,23 +11095,64 @@ function applyRedTrunkExemptions(raw, target, trunk, redSha, grantThunk, cureThu
10156
11095
  const via = cureVerdict.carveOut
10157
11096
  ? ` THROUGH THE #321 WORKFLOW CARVE-OUT — every job red on trunk ran to success here: ${cureVerdict.carveOut.jobs.map((j) => `${j.name} (${j.redMs}ms red, ${j.branchMs}ms passing)`).join(', ')}`
10158
11097
  : '';
11098
+ const viaDry = cureVerdict.dryRun ? ` — main-only job(s) ${cureVerdict.dryRun.jobs.join(', ')} proven by a DRY RUN on the branch (#474)` : '';
10159
11099
  return {
10160
11100
  name: raw.name, ok: true, class: null,
10161
- detail: `PRECONDITION OVERRIDDEN by the cure rule (#281) — branch contains red ${shortSha(redSha)} and is green at its own head${via} (raw: ${raw.detail})`,
10162
- grantVerdict: null, cureVerdict,
11101
+ detail: `PRECONDITION OVERRIDDEN by the cure rule (#281) — branch contains red ${shortSha(redSha)} and is green at its own head${via}${viaDry} (raw: ${raw.detail})`,
11102
+ grantVerdict: null, cureVerdict, redSha,
10163
11103
  };
10164
11104
  }
10165
11105
 
10166
11106
  const grantVerdict = grantThunk ? grantThunk(redSha) : null;
10167
11107
  if (grantVerdict && grantVerdict.ok) {
10168
11108
  const by = grantVerdict.granted.map((g) => '#' + g.issue).join(' ');
11109
+ // #504: a reviewer grant says so — it must never render as a human's decision.
11110
+ const rv = grantVerdict.granted.filter((g) => g.role && g.role !== 'human');
11111
+ const who = rv.length
11112
+ ? `a ${rv[0].role} ci-grant (reviewer ${[...new Set(rv.map((g) => g.reviewer))].join(', ')}, cures ${[...new Set(rv.flatMap((g) => g.cures || []))].join('; ')})`
11113
+ : 'a human ci-grant';
10169
11114
  return {
10170
11115
  name: raw.name, ok: true, class: null,
10171
- detail: `PRECONDITION OVERRIDDEN by a human ci-grant on ${by} — trunk was red at ${shortSha(redSha)} (raw: ${raw.detail})`,
10172
- grantVerdict, cureVerdict,
11116
+ detail: `PRECONDITION OVERRIDDEN by ${who} on ${by} — trunk was red at ${shortSha(redSha)} (raw: ${raw.detail})`,
11117
+ grantVerdict, cureVerdict, redSha,
10173
11118
  };
10174
11119
  }
10175
- return { ...raw, grantVerdict, cureVerdict };
11120
+ // #534: both doors were consulted and both refused — say WHY on the row itself, so the prose table,
11121
+ // `--dry`, and B1's abort line all tell "needs a grant" from "missing evidence" from "stacked". The
11122
+ // JSON payload already carried `ciCure.reason`; the prose detail used to end at the raw trunk read.
11123
+ return { ...raw, detail: `${raw.detail}${doorRefusalNote(cureVerdict, grantVerdict)}`, grantVerdict, cureVerdict, redSha };
11124
+ }
11125
+
11126
+ /**
11127
+ * Which red-trunk door let a trunk-CI row pass — `'cure rule'`, `'ci-grant'`, or null for a row that
11128
+ * passed on its own (green) or did not pass (#538: B1 re-measures only a door the table relied on).
11129
+ */
11130
+ function doorThatAdmitted(ciResult) {
11131
+ if (!ciResult || !ciResult.ok) return null;
11132
+ if (ciResult.cureVerdict && ciResult.cureVerdict.ok) return 'cure rule';
11133
+ if (ciResult.grantVerdict && ciResult.grantVerdict.ok) return 'ci-grant';
11134
+ return null;
11135
+ }
11136
+
11137
+ /** #538: the pause before B1's one re-measure — long enough for a transient `gh` failure to clear. */
11138
+ const B1_REMEASURE_MS = Number.isFinite(Number(process.env.COLAB_B1_REMEASURE_MS))
11139
+ && process.env.COLAB_B1_REMEASURE_MS !== '' ? Number(process.env.COLAB_B1_REMEASURE_MS) : 3000;
11140
+
11141
+ /**
11142
+ * The " — cure rule (#281): …; ci-grant (#105): …" suffix of a refused trunk-CI row (#534). Empty
11143
+ * when neither door was consulted. One clause per door, each its own refusal reason verbatim — the
11144
+ * cure's `reason`, the grant's per-issue `missing[].reason` — never a re-wording, so the prose and
11145
+ * the `--dry --json` fields cannot read differently.
11146
+ */
11147
+ function doorRefusalNote(cureVerdict, grantVerdict) {
11148
+ const parts = [];
11149
+ if (cureVerdict && !cureVerdict.ok && cureVerdict.reason) parts.push(`cure rule (#281): ${cureVerdict.reason}`);
11150
+ if (grantVerdict && !grantVerdict.ok) {
11151
+ const why = (grantVerdict.missing || []).map((m) => (m.issue ? `#${m.issue}: ` : '') + m.reason)
11152
+ .map((s) => s.replace(/^(#\d+): \1/, '$1')).join('; ');
11153
+ if (why) parts.push(`ci-grant (#105): ${why}`);
11154
+ }
11155
+ return parts.length ? ` — ${parts.join(' · ')}` : '';
10176
11156
  }
10177
11157
 
10178
11158
  /**
@@ -10191,12 +11171,21 @@ function shipCiGrants(repoAbs, gh, issues, branch, trunk, redSha) {
10191
11171
  missing: [{ issue: null, reason: `gh not usable (${ghUnusableWhy(repoAbs)}) — a CI grant lives on the tracker and cannot be confirmed` }] };
10192
11172
  }
10193
11173
  const records = {};
10194
- for (const n of issues) records[n] = git.ghIssueView(repoAbs, n, ['state', 'labels', 'comments']);
11174
+ // `title` (#504): a reviewer grant requires its issue to be titled `TRUNK RED:`.
11175
+ for (const n of issues) records[n] = git.ghIssueView(repoAbs, n, ['state', 'labels', 'comments', 'title']);
10195
11176
  const evRun = git.ghRunForSha(repoAbs, branch);
10196
11177
  const evidence = !evRun ? null : { ok: evRun.status === 'completed' && evRun.conclusion === 'success', sha: evRun.sha };
10197
11178
  return ciGrant.evaluateShipSet(issues, records, branch, trunk, redSha, evidence, labels.CI_GRANT_LABEL, {
10198
11179
  trust: trustAt(repoAbs, trunk),
10199
11180
  labelActors: (n) => git.ghIssueLabelActors(repoAbs, n, labels.CI_GRANT_LABEL),
11181
+ // #504 — the reviewer role: the opt-in as committed on TRUNK (never the branch), the clock for a
11182
+ // host's revoke window, and trunk's red checks at redSha, read lazily and at most once.
11183
+ policy: ciGrant.parseGrantPolicy(projectDocAt(repoAbs, trunk)).policy,
11184
+ now: Date.now(),
11185
+ redJobs: () => {
11186
+ const jobs = trunkRedRunJobs(repoAbs, trunk, redSha);
11187
+ return jobs === null ? null : ciCure.redJobSet(jobs);
11188
+ },
10200
11189
  });
10201
11190
  }
10202
11191
 
@@ -10211,7 +11200,8 @@ function ciGrantPayload(ciResult) {
10211
11200
  const g = ciResult.grantVerdict;
10212
11201
  return {
10213
11202
  ok: g.ok,
10214
- granted: g.granted.map((x) => ({ issue: x.issue, by: x.by, at: x.at, redSha: x.redSha, evidenceSha: x.evidenceSha })),
11203
+ granted: g.granted.map((x) => ({ issue: x.issue, by: x.by, at: x.at, redSha: x.redSha, evidenceSha: x.evidenceSha,
11204
+ ...(x.role ? { role: x.role, reviewer: x.reviewer, head: x.head, cures: x.cures } : {}) })),
10215
11205
  missing: g.missing.map((m) => ({ issue: m.issue, reason: m.reason })),
10216
11206
  };
10217
11207
  }
@@ -10278,11 +11268,38 @@ function shipCiCure(repoAbs, gh, target, trunk, redSha, branch) {
10278
11268
  // so a branch that cannot cure pays no job-level `gh` calls for it.
10279
11269
  const jobEvidence = (containsRedSha && evidence && evidence.ok)
10280
11270
  ? shipCureJobEvidence(repoAbs, trunk, redSha, branch, evRun) : null;
10281
- const verdict = ciCure.cureVerdict({ containsRedSha, evidence, redSha, stacking, jobEvidence,
11271
+ // #474: which workflows at the branch head offer a dry run — a static read (git show), read only
11272
+ // when job evidence exists, so a branch that already refuses on containment or 2a pays nothing.
11273
+ const capable = jobEvidence && evidence ? dryRunCapableWorkflows(repoAbs, evidence.sha) : [];
11274
+ // #510: which branch workflows a plain workflow_dispatch can run — same static read, same gating.
11275
+ const dispatchable = jobEvidence && evidence ? dispatchableWorkflows(repoAbs, evidence.sha) : [];
11276
+ // #477: a stacked refusal may be lifted by progress — measure the prior red set only then.
11277
+ const priorRedJobs = jobEvidence && stacking && stacking.stacked ? priorExemptionRedJobs(repoAbs, trunk, stacking) : null;
11278
+ const verdict = ciCure.cureVerdict({ containsRedSha, evidence, redSha, stacking, jobEvidence, priorRedJobs,
10282
11279
  workflowsTouched: diff.workflowsTouched,
10283
11280
  manifestScriptsTouched: diff.manifestScriptsTouched, manifestPaths: diff.manifestPaths,
10284
- pythonManifestTouched: diff.pythonManifestTouched, pythonManifestPaths: diff.pythonManifestPaths });
10285
- return { ...verdict, redSha, evidenceSha: evidence ? evidence.sha : null };
11281
+ manifestScriptsAddOnly: diff.manifestScriptsAddOnly,
11282
+ pythonManifestTouched: diff.pythonManifestTouched, pythonManifestPaths: diff.pythonManifestPaths,
11283
+ pythonPinOnly: diff.pythonPinOnly,
11284
+ dryRunCapable: capable.map((w) => w.name),
11285
+ dispatchable: dispatchable.map((w) => w.name), branchRuns: jobEvidence ? jobEvidence.branchRuns : null });
11286
+ // The dispatch plan carries the FILE and the exact command, so the refusal can name it and the
11287
+ // real ship path can run it — measurement only here; nothing is dispatched by this function.
11288
+ const dryRunDispatch = verdict.dryRunWanted
11289
+ ? verdict.dryRunWanted.map((name) => {
11290
+ const w = capable.find((c) => c.name === name);
11291
+ return { workflow: name, file: w.file, command: `gh workflow run ${w.file} --ref ${branch} -f ${DRY_RUN_INPUT}=true` };
11292
+ })
11293
+ : null;
11294
+ // #510: same shape for a plain workflow_dispatch of a branch workflow whose red job a push skipped.
11295
+ const dispatchCure = verdict.dispatchWanted
11296
+ ? verdict.dispatchWanted.map((name) => {
11297
+ const w = dispatchable.find((c) => c.name === name);
11298
+ return { workflow: name, file: w.file, command: `gh workflow run ${w.file} --ref ${branch}` };
11299
+ })
11300
+ : null;
11301
+ return { ...verdict, ...(dryRunDispatch ? { dryRunDispatch } : {}), ...(dispatchCure ? { dispatchCure } : {}),
11302
+ redSha, evidenceSha: evidence ? evidence.sha : null };
10286
11303
  }
10287
11304
 
10288
11305
  /**
@@ -10304,34 +11321,69 @@ function shipCiCure(repoAbs, gh, target, trunk, redSha, branch) {
10304
11321
  function shipCureJobEvidence(repoAbs, trunk, redSha, branch, evRun) {
10305
11322
  if (!evRun || !evRun.sha) return null;
10306
11323
 
10307
- // ALL runs at the red sha, not the single row `ghRunForCommit` would pick: a red job can sit in a
11324
+ const redRunJobs = trunkRedRunJobs(repoAbs, trunk, redSha);
11325
+ if (redRunJobs === null) return null;
11326
+
11327
+ const branchRuns = git.ghRunsForCommit(repoAbs, branch, evRun.sha);
11328
+ if (branchRuns === null || branchRuns.length === 0) return null;
11329
+ const branchRunJobs = [];
11330
+ for (const r of branchRuns) {
11331
+ const jobs = git.ghRunJobs(repoAbs, r.databaseId);
11332
+ if (jobs === null) return null;
11333
+ // #510: workflowId, event and headSha too — the dispatch rules (W1/W2) read them per job.
11334
+ branchRunJobs.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '', workflowId: r.workflowId ?? null,
11335
+ event: r.event || null, headSha: r.headSha || null })));
11336
+ }
11337
+
11338
+ const shaped = ciCure.shapeJobEvidence({ redRunJobs, branchRunJobs, branchSha: evRun.sha });
11339
+ // #510: the run-level rows too, for the dispatch plan's gates (d) and (e).
11340
+ return shaped && { ...shaped, branchRuns: branchRuns.map((r) => ({ workflowName: r.workflowName || '', workflowId: r.workflowId ?? null,
11341
+ event: r.event || null, status: r.status, conclusion: r.conclusion || null })) };
11342
+ }
11343
+
11344
+ /**
11345
+ * Every job of every not-green, repo-owned run on `trunk` at `sha`, each tagged with its run's
11346
+ * `workflowName` — the raw input of ci-cure.js's `shapeJobEvidence`/`redJobSet`. `null` on any failed
11347
+ * read, or when no not-green run exists there (nothing red to name). `limit` widens the run window
11348
+ * for an OLDER sha (#477's prior red sha), which a 10-row list of trunk's latest runs may not reach.
11349
+ */
11350
+ function trunkRedRunJobs(repoAbs, trunk, sha, limit) {
11351
+ // ALL runs at the sha, not the single row `ghRunForCommit` would pick: a red job can sit in a
10308
11352
  // sibling workflow the picker never returned, and admitting a carve-out while that job is still
10309
11353
  // red is exactly the failure this evidence exists to prevent.
10310
- const redRuns = git.ghRunsForCommit(repoAbs, trunk, redSha);
10311
- if (redRuns === null || redRuns.length === 0) return null;
11354
+ // #451: a run from a workflow the repo does not own is not part of trunk's red — same drop the
11355
+ // verdict itself makes (git.summarizeRunsForCommit), so cure evidence never chases its jobs.
11356
+ const runsAll = git.ghRunsForCommit(repoAbs, trunk, sha, limit);
11357
+ const runs = runsAll === null ? null : runsAll.filter(git.isRepoOwnedRun);
11358
+ if (runs === null || runs.length === 0) return null;
10312
11359
 
10313
11360
  // Same inverted allowlist git.js uses at run level (#146/#165): only `success`/`cancelled` are
10314
11361
  // not-bad, so a new not-success conclusion value is covered the day GitHub invents it.
10315
- const notGreen = redRuns.filter((r) => r.status === 'completed' && r.conclusion !== 'success' && r.conclusion !== 'cancelled');
11362
+ const notGreen = runs.filter((r) => r.status === 'completed' && r.conclusion !== 'success' && r.conclusion !== 'cancelled');
10316
11363
  if (notGreen.length === 0) return null;
10317
11364
 
10318
- const redRunJobs = [];
11365
+ const out = [];
10319
11366
  for (const r of notGreen) {
10320
11367
  const jobs = git.ghRunJobs(repoAbs, r.databaseId);
10321
11368
  if (jobs === null) return null;
10322
- redRunJobs.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '' })));
10323
- }
10324
-
10325
- const branchRuns = git.ghRunsForCommit(repoAbs, branch, evRun.sha);
10326
- if (branchRuns === null || branchRuns.length === 0) return null;
10327
- const branchRunJobs = [];
10328
- for (const r of branchRuns) {
10329
- const jobs = git.ghRunJobs(repoAbs, r.databaseId);
10330
- if (jobs === null) return null;
10331
- branchRunJobs.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '' })));
11369
+ out.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '', workflowId: r.workflowId ?? null })));
10332
11370
  }
11371
+ return out;
11372
+ }
10333
11373
 
10334
- return ciCure.shapeJobEvidence({ redRunJobs, branchRunJobs });
11374
+ /**
11375
+ * The red-job set at the red sha the prior exemption on this continuous red was measured against
11376
+ * (#477) — read only when condition 3 refused as stacked AND job evidence exists (containment + 2a
11377
+ * passed), so no other ship pays for it. The trailer's sha is usually short; it is resolved to a full
11378
+ * sha first. `null` (unmeasured → no progress → the stacked refusal stands) on any failed step.
11379
+ */
11380
+ function priorExemptionRedJobs(repoAbs, trunk, stacking) {
11381
+ const short = stacking && stacking.stacked && stacking.prior ? stacking.prior.redSha : null;
11382
+ if (!short) return null;
11383
+ const full = git.git(['rev-parse', '--verify', '--quiet', `${short}^{commit}`], repoAbs);
11384
+ if (!full.ok || !full.stdout.trim()) return null;
11385
+ const raw = trunkRedRunJobs(repoAbs, trunk, full.stdout.trim(), 100);
11386
+ return raw === null ? null : ciCure.redJobSet(raw);
10335
11387
  }
10336
11388
 
10337
11389
  /**
@@ -10357,9 +11409,132 @@ function ciCurePayload(ciResult) {
10357
11409
  carveOut: c.carveOut
10358
11410
  ? { jobs: c.carveOut.jobs.map((j) => ({ name: j.name, redDurationMs: j.redMs, branchDurationMs: j.branchMs })) }
10359
11411
  : null,
11412
+ // #474: the red job(s) proven only by a dry run of a main-only workflow — null otherwise.
11413
+ dryRun: c.dryRun ? { jobs: c.dryRun.jobs.slice() } : null,
11414
+ // #474: on a refusal, the dry run(s) that would supply the missing 2b evidence — what the real
11415
+ // ship dispatches; `--dry --json` only reports it. null when none would help.
11416
+ dryRunWanted: c.dryRunDispatch ? c.dryRunDispatch.map((d) => ({ ...d })) : null,
11417
+ // #510: the trunk-only red job(s) proven only by a workflow_dispatch run at the branch head — null otherwise.
11418
+ dispatch: c.dispatch ? { jobs: c.dispatch.jobs.slice() } : null,
11419
+ // #510: on a refusal, the workflow_dispatch run(s) that would supply the missing 2b evidence.
11420
+ dispatchWanted: c.dispatchCure ? c.dispatchCure.map((d) => ({ ...d })) : null,
11421
+ // #475/#476: the manifest change a cure was admitted with — `{scripts?, pins?}` — or null.
11422
+ admitted: c.admitted || null,
11423
+ // #477: condition 3 passed by progress past a prior exemption — `{healed, still}` — or null.
11424
+ progress: c.progress ? { healed: c.progress.healed.slice(), still: c.progress.still.slice() } : null,
10360
11425
  };
10361
11426
  }
10362
11427
 
11428
+ /** The dispatch input a dry-run-capable workflow declares (#474, templates/release-auto.yml). */
11429
+ const DRY_RUN_INPUT = 'dry_run';
11430
+
11431
+ /**
11432
+ * The workflows at `treeish` that offer a dry run (#474): a top-level `name:`, a `workflow_dispatch`
11433
+ * input named `dry_run`, and ci-cure's sentinel step text. All three, read statically at the BRANCH's
11434
+ * head — the copy a dispatch on that ref would run. A pre-#474 copy has no forced-dry mode and would
11435
+ * really publish if dispatched, which is exactly why this read gates every dispatch. `[]` on any
11436
+ * failed read: no capability is ever assumed.
11437
+ */
11438
+ function dryRunCapableWorkflows(repoAbs, treeish) {
11439
+ const ls = git.git(['ls-tree', '--name-only', `${treeish}:.github/workflows`], repoAbs);
11440
+ if (!ls.ok) return [];
11441
+ const out = [];
11442
+ for (const f of ls.stdout.split('\n').map((x) => x.trim()).filter((x) => /\.ya?ml$/.test(x))) {
11443
+ const r = git.git(['show', `${treeish}:.github/workflows/${f}`], repoAbs);
11444
+ if (!r.ok) continue;
11445
+ const name = workflowTriggers.workflowNameOf(r.stdout);
11446
+ if (!name || !r.stdout.includes(ciCure.DRY_RUN_STEP)) continue;
11447
+ if (!workflowTriggers.workflowDispatchInputs(r.stdout).includes(DRY_RUN_INPUT)) continue;
11448
+ out.push({ name, file: f });
11449
+ }
11450
+ return out;
11451
+ }
11452
+
11453
+ /**
11454
+ * The workflows at `treeish` a plain `workflow_dispatch` can run for the cure rule (#510): a top-level
11455
+ * `name:`, `workflow_dispatch` among the `on:` events, and NOT dry-run capable (those keep #474's path,
11456
+ * which forces dry mode — a plain dispatch of one would really publish). Read statically at the BRANCH's
11457
+ * head, the copy a dispatch on that ref runs. Whether it is branch CI rather than a main-only workflow is
11458
+ * gate (d) in ci-cure's `cureDispatchPlan`, read off the runs. `[]` on any failed read.
11459
+ */
11460
+ function dispatchableWorkflows(repoAbs, treeish) {
11461
+ const ls = git.git(['ls-tree', '--name-only', `${treeish}:.github/workflows`], repoAbs);
11462
+ if (!ls.ok) return [];
11463
+ const out = [];
11464
+ for (const f of ls.stdout.split('\n').map((x) => x.trim()).filter((x) => /\.ya?ml$/.test(x))) {
11465
+ const r = git.git(['show', `${treeish}:.github/workflows/${f}`], repoAbs);
11466
+ if (!r.ok) continue;
11467
+ const name = workflowTriggers.workflowNameOf(r.stdout);
11468
+ if (!name || r.stdout.includes(ciCure.DRY_RUN_STEP)) continue;
11469
+ if (!workflowTriggers.parseWorkflowOn(r.stdout).events.has('workflow_dispatch')) continue;
11470
+ out.push({ name, file: f });
11471
+ }
11472
+ return out;
11473
+ }
11474
+
11475
+ /**
11476
+ * Dispatch the workflow_dispatch run(s) a refused cure asked for (#510) — the REAL ship path only, the
11477
+ * same posture as `shipDispatchDryRuns` below. Skips a workflow that already has a `workflow_dispatch`
11478
+ * run at the branch head, whatever its status. Never waits: the job it runs may take hours, and ship's
11479
+ * measurement runs up to three times per invocation — the caller waits with `colab ci-wait` and re-runs.
11480
+ */
11481
+ function shipDispatchCure(repoAbs, branch, plan) {
11482
+ const head = git.git(['rev-parse', branch], repoAbs);
11483
+ const sha = head.ok ? head.stdout.trim() : '';
11484
+ const runs = sha ? git.ghRunsForCommit(repoAbs, branch, sha, 30) : null;
11485
+ for (const p of plan) {
11486
+ const existing = runs ? runs.filter((r) => r.workflowName === p.workflow && r.event === 'workflow_dispatch') : null;
11487
+ if (existing === null) {
11488
+ warn(` workflow_dispatch of ${p.workflow} NOT made: the runs at ${branch}'s head could not be read — run it yourself: ${p.command}`);
11489
+ continue;
11490
+ }
11491
+ if (existing.length) {
11492
+ const r = existing[0];
11493
+ warn(` a workflow_dispatch run of ${p.workflow} already exists at ${branch}'s head (run ${r.databaseId}, ${r.status}${r.conclusion ? '/' + r.conclusion : ''}) — not dispatched again; re-run \`colab ship\` once it completes.`);
11494
+ continue;
11495
+ }
11496
+ const d = git.ghWorkflowDispatch(repoAbs, p.file, branch, {});
11497
+ if (d.ok) {
11498
+ warn(` ↻ dispatched ${p.workflow} on ${branch} (#510) — it runs the trunk-only job(s) the branch push skipped. ` +
11499
+ `Wait with \`colab ci-wait --sha ${sha} --branch ${branch} --timeout <the job's usual length>\`, then re-run \`colab ship\`.`);
11500
+ } else {
11501
+ warn(` ${p.workflow} could NOT be dispatched (${d.detail}) — run it yourself: ${p.command}`);
11502
+ }
11503
+ }
11504
+ }
11505
+
11506
+ /**
11507
+ * Dispatch the dry run(s) a refused cure asked for (#474) — the REAL ship path only, never `--dry`,
11508
+ * never `--dry --json`, never from the measurement above (which runs up to three times per ship).
11509
+ * Skips a workflow that already has ANY run at the branch head, whatever its status: a queued run has
11510
+ * no jobs yet, so "job absent" alone would dispatch it twice. Never waits — the caller re-runs ship
11511
+ * once the run completes (code-ship B1a's bounded wait), the same no-polling stance as every other
11512
+ * read here.
11513
+ */
11514
+ function shipDispatchDryRuns(repoAbs, branch, plan) {
11515
+ const head = git.git(['rev-parse', branch], repoAbs);
11516
+ const runs = head.ok ? git.ghRunsForCommit(repoAbs, branch, head.stdout.trim(), 30) : null;
11517
+ for (const p of plan) {
11518
+ const existing = runs ? runs.filter((r) => r.workflowName === p.workflow) : null;
11519
+ if (existing === null) {
11520
+ warn(` dry run for ${p.workflow} NOT dispatched: the runs at ${branch}'s head could not be read — run it yourself: ${p.command}`);
11521
+ continue;
11522
+ }
11523
+ if (existing.length) {
11524
+ const r = existing[0];
11525
+ warn(` dry run for ${p.workflow} already exists at ${branch}'s head (run ${r.databaseId}, ${r.status}${r.conclusion ? '/' + r.conclusion : ''}) — not dispatched again; re-run \`colab ship\` once it completes.`);
11526
+ continue;
11527
+ }
11528
+ const d = git.ghWorkflowDispatch(repoAbs, p.file, branch, { [DRY_RUN_INPUT]: 'true' });
11529
+ if (d.ok) {
11530
+ warn(` ↻ dispatched a dry run of ${p.workflow} on ${branch} (#474)${d.withInputs ? '' : ' — without the input, which GitHub refused; the ref forces dry mode'}. ` +
11531
+ 'Re-run `colab ship` once it completes (code-ship B1a\'s bounded wait) — it is the evidence this cure is missing.');
11532
+ } else {
11533
+ warn(` dry run for ${p.workflow} could NOT be dispatched (${d.detail}) — run it yourself: ${p.command}`);
11534
+ }
11535
+ }
11536
+ }
11537
+
10363
11538
  /**
10364
11539
  * Previews whether B0's merge (target INTO the branch) would conflict — WITHOUT touching the real
10365
11540
  * worktree, the branch, or the network beyond a fetch — so `ship --dry --json`'s "no hand-merge
@@ -10519,7 +11694,8 @@ function cmdShipDryJson(opts) {
10519
11694
  }
10520
11695
 
10521
11696
  // ---- (a) AUTONOMY GATE — does NOT short-circuit here; an unattended caller wants the whole table ----
10522
- const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)));
11697
+ const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)),
11698
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
10523
11699
  autonomyGatePayloadVal = autonomyGatePayload(autonomyGate);
10524
11700
  checks.push({ name: 'autonomy granted', ok: autonomyGate.ok, class: autonomyGate.ok ? null : HUMAN_GATED, detail: autonomyGate.detail });
10525
11701
 
@@ -10527,7 +11703,7 @@ function cmdShipDryJson(opts) {
10527
11703
  const gh = isGhUsable(repoAbs);
10528
11704
  const ciResultJson = shipCiCheck(repoAbs, gh, target, trunk,
10529
11705
  (redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
10530
- (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch));
11706
+ (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
10531
11707
  ciGrantPayloadVal = ciGrantPayload(ciResultJson);
10532
11708
  ciCurePayloadVal = ciCurePayload(ciResultJson);
10533
11709
  checks.push({ name: ciResultJson.name, ok: ciResultJson.ok, class: ciResultJson.class, detail: ciResultJson.detail });
@@ -10789,14 +11965,21 @@ function shipMode(repoAbs, target, branch, commits) {
10789
11965
  */
10790
11966
  function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
10791
11967
  const seen = new Set();
11968
+ const tr = tracker.forRepo(repoAbs);
10792
11969
  for (const start of closedIssues || []) {
10793
11970
  let child = start;
10794
11971
  for (let depth = 0; depth < 5; depth++) {
10795
- const view = git.ghIssueView(repoAbs, child, ['parent']);
11972
+ const view = tr.issueView(child, ['parent', 'url']);
10796
11973
  const pnum = view && view.parent && Number.isInteger(view.parent.number) ? view.parent.number : null;
10797
11974
  if (pnum === null || seen.has(pnum)) break;
11975
+ // #502: the parent's NUMBER means something only in the parent's own repository. A cross-repo
11976
+ // parent looked up here would read nothing (a misleading "could not read") or an unrelated
11977
+ // issue sharing the number — which could be classified and closed. Never evaluated from here.
11978
+ const rel = containerClose.parentRelation(view);
11979
+ if (rel.relation === 'other') { print(` container ${containerClose.parentRelationFinding(rel)} (#502)`); break; }
11980
+ if (rel.relation !== 'same') { warn(`container ${containerClose.parentRelationFinding(rel)}`); break; }
10798
11981
  seen.add(pnum);
10799
- const parent = git.ghIssueView(repoAbs, pnum, ['number', 'state', 'labels', 'body', 'subIssuesSummary']);
11982
+ const parent = tr.issueView(pnum, ['number', 'state', 'labels', 'body', 'subIssuesSummary']);
10800
11983
  const c = containerClose.classifyContainer(parent || null);
10801
11984
  if (c.verdict !== 'close') {
10802
11985
  const finding = containerClose.containerFinding({ ...c, number: c.number === null ? pnum : c.number });
@@ -10807,7 +11990,7 @@ function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
10807
11990
  const cm = git.ghIssueComment(repoAbs, pnum, body);
10808
11991
  if (!cm.ok) warnDeferred(`could not post the container-close comment on #${pnum} — left OPEN`);
10809
11992
  if (!cm.ok) break;
10810
- const r = git.run('gh', ['issue', 'close', String(pnum), '--reason', 'completed'], { cwd: repoAbs });
11993
+ const r = tr.issueClose(pnum, { reason: 'completed' });
10811
11994
  if (!r.ok) { warnDeferred(`could not close container #${pnum}: ${(r.stderr || '').split('\n')[0]}`); break; }
10812
11995
  print(` closed container #${pnum} — all ${c.total} sub-issue(s) closed (#371)`);
10813
11996
  for (const d of containerClose.containerDeliveryLabels(parent.labels)) warn(`container #${pnum} carried ${d} — a container has no deliverable of its own (#371)`);
@@ -10817,7 +12000,14 @@ function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
10817
12000
  }
10818
12001
 
10819
12002
  function shipJournalPlanFiles(repoAbs, issues) {
10820
- const plansDir = path.join(repoAbs, '.claude', 'plans');
12003
+ // #488: the configured plans dir first, then the legacy `.claude/plans/` — a plan written before
12004
+ // the switch is still journalled and deleted. One journal line per issue across both dirs: a
12005
+ // stray duplicate in the second dir is deleted without journalling the issue twice.
12006
+ const journalled = new Set();
12007
+ for (const plansDir of scratchDirs.planReadDirs(repoAbs)) shipJournalPlanDir(repoAbs, plansDir, issues, journalled);
12008
+ }
12009
+
12010
+ function shipJournalPlanDir(repoAbs, plansDir, issues, journalled) {
10821
12011
  let entries;
10822
12012
  try { entries = fs.readdirSync(plansDir); } catch (_) { return; } // no plans dir at all — nothing to do
10823
12013
  const issueSet = new Set(issues.map((n) => String(n)));
@@ -10834,13 +12024,17 @@ function shipJournalPlanFiles(repoAbs, issues) {
10834
12024
  const rm = txt.match(/^rung:\s*(.+)$/m); if (rm) rung = rm[1].trim();
10835
12025
  const cm = txt.match(/^cause:\s*(.+)$/m); if (cm) cause = cm[1].trim();
10836
12026
  } catch (_) { /* front matter is optional — the defaults above cover a plain rung-1 stub */ }
10837
- const lines = nums.map((num) => JSON.stringify({
12027
+ const fresh = nums.filter((num) => !journalled.has(num));
12028
+ const lines = fresh.map((num) => JSON.stringify({
10838
12029
  ts: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
10839
12030
  issue: Number(num), rung, cause, verdict: 'pass',
10840
- })).join('\n') + '\n';
12031
+ })).join('\n');
10841
12032
  try {
10842
- fs.mkdirSync(path.dirname(journalPath), { recursive: true });
10843
- fs.appendFileSync(journalPath, lines);
12033
+ if (lines) {
12034
+ fs.mkdirSync(path.dirname(journalPath), { recursive: true });
12035
+ fs.appendFileSync(journalPath, lines + '\n');
12036
+ }
12037
+ for (const num of fresh) journalled.add(num);
10844
12038
  fs.rmSync(planPath, { force: true }); // only after the journal write above landed
10845
12039
  } catch (e) {
10846
12040
  warnDeferred(`could not journal/delete the plan file "${name}" (${e.message}) — left in place`);
@@ -10900,9 +12094,9 @@ function shipEvidenceClose({ repoAbs, st, sess, target, trunk, gh, closeIssues,
10900
12094
  `The deliverable is recorded on this issue (see the comment(s) above), which is what authorised ` +
10901
12095
  `the close — colab closes a zero-diff issue only when it already carries a comment colab did not ` +
10902
12096
  `write. The zero-diff fact was measured from git: ${mode.why}.${shipSess}`;
10903
- const c = git.ghIssueComment(repoAbs, num, body);
12097
+ const c = git.ghIssueComment(repoAbs, num, body + (opts.humanDoorEvidence || '')); // #525
10904
12098
  if (!c.ok) warn(`could not post the evidence-close comment on #${num} — closing anyway`);
10905
- const r = git.run('gh', ['issue', 'close', String(num), '--reason', 'completed'], { cwd: repoAbs });
12099
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: 'completed' });
10906
12100
  if (!r.ok) { skipped.push({ num, why: `gh issue close failed: ${(r.stderr || '').split('\n')[0]}` }); continue; }
10907
12101
  closed.push(num);
10908
12102
  print(` #${num} closed with evidence.`);
@@ -11062,7 +12256,8 @@ function cmdShipDirect(opts) {
11062
12256
  // #345: a trunk-direct unit has no branch diff. Its change set is every trunk commit since its
11063
12257
  // earliest claim — by anyone, so the verdict can only err toward refusing (lib/docs-only.js).
11064
12258
  const since = claims.map((c) => c.created).filter(Boolean).sort()[0];
11065
- const autonomyGate = shipAutonomyGate(doc, () => docsOnly.directChanges(git, repoAbs, trunk, since));
12259
+ const autonomyGate = shipAutonomyGate(doc, () => docsOnly.directChanges(git, repoAbs, trunk, since),
12260
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
11066
12261
  autonomyGatePayloadVal = autonomyGatePayload(autonomyGate);
11067
12262
  checks.push({ name: 'autonomy granted', ok: autonomyGate.ok, class: autonomyGate.ok ? null : HUMAN_GATED, detail: autonomyGate.detail });
11068
12263
 
@@ -11141,6 +12336,7 @@ function cmdShipDirect(opts) {
11141
12336
  process.stderr.write(`✗ ${shortRepo(repoAbs)} does not grant auto-trunk (project.yml autonomy: ${autonomyGate.declared}).\n`);
11142
12337
  process.stderr.write(' A human must close this unit. (Autonomy is granted by the repo, not by a flag — --force cannot override.)\n');
11143
12338
  process.stderr.write(` The docs-only exception (#345) does not apply either: ${autonomyGate.docsOnly.reason}.\n`);
12339
+ process.stderr.write(shipHumanDoorRefusal(autonomyGate, '--direct'));
11144
12340
  return 1;
11145
12341
  }
11146
12342
  if (!coreOk && coreReview.corePaths.length) {
@@ -11152,15 +12348,19 @@ function cmdShipDirect(opts) {
11152
12348
  process.stderr.write(' unit\'s reviewed landing, a human closes this issue by hand.\n');
11153
12349
  }
11154
12350
  if (autonomyGate.via === 'docs-only') print(`→ AUTONOMY: ${autonomyGate.detail} (#345) — project.yml autonomy: ${autonomyGate.declared}`);
12351
+ if (autonomyGate.via === 'human') print(`→ AUTONOMY: ${autonomyGate.detail}`);
11155
12352
  print(`→ MODE: evidence-close (trunk-direct — the work is already on ${trunk}; nothing to merge)`);
11156
12353
  if (opts.dry) {
11157
12354
  print(preOk ? '→ READY: preconditions pass. Re-run without --dry to close.' : '→ NOT READY: fix the ✗ rows above.');
11158
12355
  print(' Plan: no merge, no commit, no push · post evidence comment + CLOSE each issue · release the claims (and the checkout hold)');
11159
12356
  print(' Gate: every closing issue must already carry an evidence comment — checked at run time.');
12357
+ // #479: show BOTH halves of the split, so a wrong one is visible before the push.
12358
+ if (closeIssues.length) print(` Closes (closed by this ship): ${closeIssues.map((n) => '#' + n).join(' ')}`);
11160
12359
  if (refsIssues.length) print(` Refs (kept open, NOT closed): ${refsIssues.map((n) => '#' + n).join(' ')}`);
11161
12360
  return preOk ? 0 : 1;
11162
12361
  }
11163
12362
  if (!preOk) { process.stderr.write('✗ Aborting: one or more preconditions failed (see ✗ above). Nothing was closed.\n'); return 1; }
12363
+ if (!shipHumanDoorGo(autonomyGate, opts, `close ${issues.map((n) => '#' + n).join(' ')} on ${trunk} (trunk-direct)`)) return 1;
11164
12364
 
11165
12365
  const tip = shortSha(git.git(['rev-parse', trunk], repoAbs).stdout);
11166
12366
  const mode = { evidenceClose: true, direct: true, why: `trunk-direct unit — ${trunk}@${tip} is checked out clean and published to ${git.remoteInfo(repoAbs).name || 'origin'}/${trunk}` };
@@ -11186,6 +12386,19 @@ function readTargetCodeowners(repoAbs, target) {
11186
12386
  return null;
11187
12387
  }
11188
12388
 
12389
+ /**
12390
+ * #483: is this repo a fork, and which org owns it? The fork test is adopt's own (#449: a remote named
12391
+ * `upstream` whose URL differs from origin's), so adopt and ship never disagree about the shape; the
12392
+ * owner is read from this repo's remote URL. Either unknown → `{ fork: false }`, nothing is dropped.
12393
+ */
12394
+ function codeownersForkContext(repoAbs) {
12395
+ if (!adoptDetectFork(repoAbs)) return { fork: false, ownOrg: null };
12396
+ const name = git.remoteInfo(repoAbs).name || 'origin';
12397
+ const u = git.git(['remote', 'get-url', name], repoAbs);
12398
+ const ownOrg = u.ok ? codeowners.remoteOwner(u.stdout) : null;
12399
+ return { fork: !!ownOrg, ownOrg };
12400
+ }
12401
+
11189
12402
  function branchChangedPathsNoRenames(repoAbs, base, ref) {
11190
12403
  const r = git.git(['diff', '--name-only', '--no-renames', `${base}...${ref}`], repoAbs);
11191
12404
  return r.ok ? r.stdout.split('\n').map((s) => s.trim()).filter(Boolean) : null;
@@ -11229,21 +12442,30 @@ function shipDirectCoreReview(repoAbs, gh, trunk, since) {
11229
12442
  }
11230
12443
  }
11231
12444
  }
11232
- return codeowners.directVerdict({ files: [before, readTargetCodeowners(repoAbs, trunk)], authors, changed });
12445
+ return codeowners.directVerdict({ files: [before, readTargetCodeowners(repoAbs, trunk)], authors, changed, fork: codeownersForkContext(repoAbs) });
11233
12446
  }
11234
12447
 
11235
12448
  function shipCoreReview(repoAbs, gh, target, branch) {
11236
- const out = { active: false, inertReason: null, codeownersPath: null, warnings: [], corePaths: [],
12449
+ const out = { active: false, inertReason: null, codeownersPath: null, warnings: [], corePaths: [], ignoredOwners: [],
11237
12450
  pr: null, approval: null, headSha: null, authors: [], verdict: 'inert', detail: '' };
11238
12451
  const file = readTargetCodeowners(repoAbs, target);
11239
12452
  if (!file) { out.inertReason = `no CODEOWNERS on ${target}`; out.detail = `inert: ${out.inertReason}`; return out; }
11240
12453
  out.codeownersPath = file.path;
11241
- const { rules, warnings } = codeowners.parse(file.text);
11242
- out.warnings = warnings;
12454
+ const parsedFile = codeowners.parse(file.text);
12455
+ out.warnings = parsedFile.warnings;
12456
+ // #483: on a fork, teams of another org (inherited from the upstream) bind nothing here.
12457
+ const forkCtx = codeownersForkContext(repoAbs);
12458
+ const { rules, dropped } = codeowners.dropForeignTeams(parsedFile.rules, forkCtx);
12459
+ out.ignoredOwners = dropped;
12460
+ if (dropped.length) out.warnings = [...out.warnings, codeowners.foreignNote(dropped, forkCtx)];
11243
12461
  const parsed = branchName.parse(branch);
11244
12462
  out.authors = [...new Set([gh ? git.ghCurrentLogin() : null, parsed && parsed.login].filter(Boolean))];
11245
12463
  const inert = codeowners.inert(rules, out.authors);
11246
- if (inert.inert) { out.inertReason = inert.reason; out.detail = `inert: ${inert.reason}`; return out; }
12464
+ if (inert.inert) {
12465
+ out.inertReason = dropped.length ? `${inert.reason} once the fork's inherited foreign-org teams are ignored (#483)` : inert.reason;
12466
+ out.detail = `inert: ${out.inertReason}`;
12467
+ return out;
12468
+ }
11247
12469
  out.active = true;
11248
12470
  const ref = shipRefFor(repoAbs, branch);
11249
12471
  out.headSha = git.git(['rev-parse', ref], repoAbs).stdout || null;
@@ -11304,7 +12526,7 @@ function coreReviewPayload(cr) {
11304
12526
  if (!cr) return null;
11305
12527
  return {
11306
12528
  active: cr.active, verdict: cr.verdict, inertReason: cr.inertReason, codeownersPath: cr.codeownersPath,
11307
- corePaths: cr.corePaths.map((c) => c.path), headSha: cr.headSha,
12529
+ ignoredOwners: cr.ignoredOwners || [], corePaths: cr.corePaths.map((c) => c.path), headSha: cr.headSha,
11308
12530
  pr: cr.pr ? { number: cr.pr.number, url: cr.pr.url, state: cr.pr.state } : null,
11309
12531
  approval: cr.approval,
11310
12532
  };
@@ -11356,20 +12578,81 @@ function shipOpenCorePr(repoAbs, cr, { target, branch, title, body }) {
11356
12578
  *
11357
12579
  * Returns `{ ok, via: 'auto-trunk'|'docs-only'|null, declared, docsOnly: verdict|null, detail }`.
11358
12580
  */
11359
- function shipAutonomyGate(doc, readDocsOnly) {
12581
+ function shipAutonomyGate(doc, readDocsOnly, door = null) {
11360
12582
  const declared = doc.autonomy ? String(doc.autonomy) : 'absent';
11361
- if (declared === 'auto-trunk') return { ok: true, via: 'auto-trunk', declared, docsOnly: null, detail: 'auto-trunk' };
12583
+ if (declared === 'auto-trunk') return { ok: true, via: 'auto-trunk', declared, docsOnly: null, human: null, detail: 'auto-trunk' };
11362
12584
  const verdict = readDocsOnly();
11363
12585
  if (verdict.docsOnly) {
11364
- return { ok: true, via: 'docs-only', declared, docsOnly: verdict, detail: `${verdict.reason} — autonomy exception` };
12586
+ return { ok: true, via: 'docs-only', declared, docsOnly: verdict, human: null, detail: `${verdict.reason} — autonomy exception` };
12587
+ }
12588
+ // #525: the human door — the person running ship IS the go (ruling on #525, option 1). Checked
12589
+ // after docs-only, so a docs-only change keeps its own (agent-usable) door and record.
12590
+ if (door && door.open) {
12591
+ return { ok: true, via: 'human', declared, docsOnly: verdict, human: door,
12592
+ detail: `human door (#525): ${door.why} — project.yml autonomy: ${declared}` };
11365
12593
  }
11366
- return { ok: false, via: null, declared, docsOnly: verdict,
11367
- detail: `project.yml autonomy: ${declared} — a human must trigger Phase B (not docs-only: ${verdict.reason})` };
12594
+ return { ok: false, via: null, declared, docsOnly: verdict, human: door,
12595
+ detail: `project.yml autonomy: ${declared} — a human must trigger Phase B (not docs-only: ${verdict.reason}; human door closed: ${door ? door.why : 'not offered'})` };
12596
+ }
12597
+
12598
+ /** #525: the human-door refusal lines — what a person runs, never just "a human must". */
12599
+ function shipHumanDoorRefusal(gate, selector) {
12600
+ const lines = [];
12601
+ if (gate.human && gate.human.why) lines.push(` The human door (#525) did not open: ${gate.human.why}.`);
12602
+ lines.push(' A person gives the go by running ship themselves — every other precondition still applies:');
12603
+ for (const l of humanDoor.humanDoorCommands(selector)) lines.push(` ${l}`);
12604
+ lines.push(' An agent does not pass this door on its own (CONVENTIONS.md §2, *The human door*).');
12605
+ return lines.join('\n') + '\n';
12606
+ }
12607
+
12608
+ /** #525: the ship selector to paste into the refusal's command line. */
12609
+ function shipSelector(opts, sess) {
12610
+ if (opts.direct) return '--direct';
12611
+ if (opts.worktree) return `--worktree ${opts.worktree}`;
12612
+ if (sess && sess.name) return `--worktree ${sess.name}`;
12613
+ if (opts.branch) return `--branch ${opts.branch}`;
12614
+ return sess && sess.branch ? `--branch ${sess.branch}` : '';
12615
+ }
12616
+
12617
+ /**
12618
+ * #525: confirm the TTY door by a typed answer. Synchronous on purpose — ship is a sync pipeline,
12619
+ * and the prompt sits before any write. Anything but `y`/`yes` is a no; EOF is a no.
12620
+ */
12621
+ function shipConfirmAtTerminal(question) {
12622
+ process.stdout.write(`${question} [y/N] `);
12623
+ const buf = Buffer.alloc(256);
12624
+ let line = '';
12625
+ for (;;) {
12626
+ let n = 0;
12627
+ try { n = fs.readSync(0, buf, 0, buf.length, null); } catch (e) { if (e.code === 'EAGAIN') continue; return false; }
12628
+ if (n <= 0) break;
12629
+ line += buf.toString('utf8', 0, n);
12630
+ if (line.includes('\n')) break;
12631
+ }
12632
+ return /^\s*y(es)?\s*$/i.test(line.split('\n')[0]);
12633
+ }
12634
+
12635
+ /**
12636
+ * #525: the last step before any write when the human door opened the gate. A TTY door asks the
12637
+ * person to confirm; a COLAB_HUMAN door already carries its go (`--answered-by`). Either way the
12638
+ * evidence clause is stashed on `opts` for the comment writers. Returns false on a declined prompt.
12639
+ */
12640
+ function shipHumanDoorGo(gate, opts, what) {
12641
+ if (gate.via !== 'human') return true;
12642
+ if (gate.human.how === 'tty' && !shipConfirmAtTerminal(`Human door (#525): ${what}. This is your go — proceed?`)) {
12643
+ process.stderr.write('✗ Not confirmed at the terminal. Nothing was changed.\n');
12644
+ return false;
12645
+ }
12646
+ opts.humanDoorEvidence = humanDoor.humanDoorEvidence(gate.human);
12647
+ return true;
11368
12648
  }
11369
12649
 
11370
12650
  /** #345: the additive `autonomyGate` field of the `--dry --json` output. */
11371
12651
  function autonomyGatePayload(gate) {
11372
- return { via: gate.via, docsOnly: gate.docsOnly };
12652
+ // #525: `human` is additive and present only when the human door was consulted, so an
12653
+ // auto-trunk / docs-only payload stays byte-identical to before.
12654
+ return gate.human ? { via: gate.via, docsOnly: gate.docsOnly, human: { open: gate.human.open, how: gate.human.how, why: gate.human.why } }
12655
+ : { via: gate.via, docsOnly: gate.docsOnly };
11373
12656
  }
11374
12657
 
11375
12658
  /** The sha a branch name resolves to, local first, else origin's copy (#324's remote-only shape). */
@@ -11380,7 +12663,13 @@ function shipRefFor(repoAbs, branch) {
11380
12663
 
11381
12664
  function cmdShip(argv) {
11382
12665
  const opts = parseArgs(argv, {
11383
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--refs': 'refs', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch' },
12666
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch', '--answered-by': 'answeredBy' },
12667
+ // #479: a repeated --refs used to keep only its LAST value, and every dropped issue then became a
12668
+ // `Closes` line on trunk — an issue meant to stay open, auto-closed by the push. --refs now
12669
+ // accumulates (a repeat is the same as one comma list); every OTHER value flag to ship refuses a
12670
+ // repeat (`once`), checked here before any git or GitHub call.
12671
+ lists: { '--refs': 'refs' },
12672
+ once: true,
11384
12673
  flags: { '--keep-worktree': 'keepWorktree', '--delete-branch': 'deleteBranch', '--keep-branch': 'keepBranch', '--dry': 'dry', '--json': 'json', '--direct': 'direct', '--adopt': 'adopt', '-h': 'help', '--help': 'help' },
11385
12674
  });
11386
12675
  if (opts.help) return print(HELP_SHIP);
@@ -11449,11 +12738,13 @@ function cmdShip(argv) {
11449
12738
 
11450
12739
  // ---- (a) AUTONOMY GATE — granted by the repo file, never by the caller ----
11451
12740
  // #345: …or the branch's diff is documentation only, computed here from git — never asserted.
11452
- const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)));
12741
+ const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)),
12742
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
11453
12743
  if (!autonomyGate.ok) {
11454
12744
  process.stderr.write(`✗ ${shortRepo(repoAbs)} does not grant auto-trunk (project.yml autonomy: ${autonomyGate.declared}).\n`);
11455
12745
  process.stderr.write(' A human must trigger Phase B. (Autonomy is granted by the repo, not by a flag — --force cannot override.)\n');
11456
12746
  process.stderr.write(` The docs-only exception (#345) does not apply either: ${autonomyGate.docsOnly.reason}.\n`);
12747
+ process.stderr.write(shipHumanDoorRefusal(autonomyGate, shipSelector(opts, sess)));
11457
12748
  return 1;
11458
12749
  }
11459
12750
 
@@ -11501,7 +12792,7 @@ function cmdShip(argv) {
11501
12792
  // ordinary green-trunk ship makes zero extra `gh` reads for a door nobody needs.
11502
12793
  const ciResult = shipCiCheck(repoAbs, gh, target, trunk,
11503
12794
  (redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
11504
- (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch));
12795
+ (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
11505
12796
  const ciOk = ciResult.ok;
11506
12797
  checks.push([ciResult.ok ? '✓' : '✗', ciResult.name, ciResult.detail]);
11507
12798
 
@@ -11792,6 +13083,16 @@ function cmdShip(argv) {
11792
13083
  }
11793
13084
  const dryOk = preOk && dryClosingConflicts.length === 0;
11794
13085
  print(dryOk ? '→ READY: preconditions pass. Re-run without --dry to ship.' : '→ NOT READY: fix the ✗ rows above.');
13086
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dryRunDispatch) {
13087
+ for (const d of ciResult.cureVerdict.dryRunDispatch) {
13088
+ print(` Dry run wanted (#474): ${d.workflow} has no run on this branch — a real \`colab ship\` dispatches \`${d.command}\` and refuses until it completes.`);
13089
+ }
13090
+ }
13091
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dispatchCure) {
13092
+ for (const d of ciResult.cureVerdict.dispatchCure) {
13093
+ print(` Dispatch wanted (#510): ${d.workflow} skipped the red job(s) on this branch's push — a real \`colab ship\` dispatches \`${d.command}\` and refuses until it completes.`);
13094
+ }
13095
+ }
11795
13096
  if (mode.evidenceClose) {
11796
13097
  print(' Plan: no merge, no commit, no push · post evidence comment + CLOSE each issue · ' +
11797
13098
  (opts.keepWorktree ? 'keep worktree' : 'worktree rm') + ' (releases claims)');
@@ -11819,10 +13120,26 @@ function cmdShip(argv) {
11819
13120
  print(` ✗ "${c.keyword} #${c.num}" would close #${c.num} on merge — kept open by --refs; reword the commit before shipping.`);
11820
13121
  }
11821
13122
  }
13123
+ // #479: show BOTH halves of the split, so a wrong one is visible before the push.
13124
+ if (closeIssues.length) print(` Closes (closed by this ship): ${closeIssues.map((n) => '#' + n).join(' ')}`);
11822
13125
  if (refsIssues.length) print(` Refs (kept open, NOT closed): ${refsIssues.map((n) => '#' + n).join(' ')}`);
11823
13126
  return dryOk ? 0 : 1;
11824
13127
  }
11825
- if (!preOk) { process.stderr.write('✗ Aborting: one or more preconditions failed (see ✗ above). Nothing was pushed.\n'); return 1; }
13128
+ if (!preOk) {
13129
+ // #474: the cure is missing only a main-only workflow's run, and that workflow offers a dry run —
13130
+ // dispatch it now (once), so the re-run has the evidence. Never on --dry: that returned above.
13131
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dryRunDispatch && gh) {
13132
+ shipDispatchDryRuns(repoAbs, sess.branch, ciResult.cureVerdict.dryRunDispatch);
13133
+ }
13134
+ // #510: same, for a branch workflow whose red job the push skipped — a plain workflow_dispatch.
13135
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dispatchCure && gh) {
13136
+ shipDispatchCure(repoAbs, sess.branch, ciResult.cureVerdict.dispatchCure);
13137
+ }
13138
+ process.stderr.write('✗ Aborting: one or more preconditions failed (see ✗ above). Nothing was pushed.\n'); return 1;
13139
+ }
13140
+ if (!shipHumanDoorGo(autonomyGate, opts, mode.evidenceClose
13141
+ ? `evidence-close ${sess.issues.map((n) => '#' + n).join(' ')} (${sess.branch} has nothing to merge)`
13142
+ : `squash-merge ${sess.branch} into ${target}`)) return 1;
11826
13143
 
11827
13144
  // ---- (b3) evidence-close: the whole B0–B2 sequence is skipped, because there is nothing to merge ----
11828
13145
  if (mode.evidenceClose) return shipEvidenceClose({
@@ -11925,7 +13242,8 @@ function cmdShip(argv) {
11925
13242
  if (coreReview.verdict === 'approved') {
11926
13243
  const reviewed = new Set(coreReview.corePaths.map((c) => c.path));
11927
13244
  const nowChanged = branchChangedPathsNoRenames(repoAbs, mergeRef, sess.branch) || [];
11928
- const { rules } = codeowners.parse((readTargetCodeowners(repoAbs, target) || {}).text || '');
13245
+ const { rules } = codeowners.dropForeignTeams(
13246
+ codeowners.parse((readTargetCodeowners(repoAbs, target) || {}).text || '').rules, codeownersForkContext(repoAbs));
11929
13247
  const unreviewed = codeowners.corePaths(rules, nowChanged).filter((c) => !reviewed.has(c.path));
11930
13248
  if (unreviewed.length) {
11931
13249
  cleanupEphemeral();
@@ -11946,12 +13264,29 @@ function cmdShip(argv) {
11946
13264
  let ciGrantForTrailer = null; // #105: set below when B1 shipped UNDER a grant — read at commit-message time
11947
13265
  let ciCureForTrailer = null; // #281: set below when B1 shipped UNDER the cure rule — read at commit-message time
11948
13266
  if (gh) {
11949
- const ciResultB1 = shipCiCheck(repoAbs, gh, target, trunk,
13267
+ const measureB1 = () => shipCiCheck(repoAbs, gh, target, trunk,
11950
13268
  (redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
11951
- (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch));
13269
+ (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
13270
+ let ciResultB1 = measureB1();
13271
+ // #538: the table admitted this branch through a door (cure or grant) at red sha X, and B1 —
13272
+ // seconds later, at the SAME red sha — refused. Nothing the door judges moved (trunk's head is
13273
+ // X in both reads), so the likeliest cause is one of the ~10 `gh` reads a door makes failing
13274
+ // once, which every door reads as a refusal (fail closed). Measured: `--dry` said READY and the
13275
+ // real ship aborted here with only the raw "conclusion=failure". Re-measure ONCE, in full —
13276
+ // never reuse the table's verdict (B1 exists to catch a change) — and if it refuses again, abort
13277
+ // saying it was the door, with the door's own reason.
13278
+ const tableDoor = doorThatAdmitted(ciResult);
13279
+ if (!ciResultB1.ok && tableDoor && ciResultB1.redSha && ciResultB1.redSha === ciResult.redSha) {
13280
+ warn(` B1: the ${tableDoor} admitted this branch in the table at ${target}@${shortSha(ciResult.redSha)} but refused on the re-check at the same sha — re-measuring once (a failed read refuses).`);
13281
+ ciWait.sleepSync(B1_REMEASURE_MS);
13282
+ ciResultB1 = measureB1();
13283
+ }
11952
13284
  if (!ciResultB1.ok) {
11953
13285
  cleanupEphemeral();
11954
- process.stderr.write(`✗ B1: CI for ${target} is no longer green — aborting before merge. Nothing pushed. (${ciResultB1.detail})\n`);
13286
+ const sameRed = tableDoor && ciResultB1.redSha && ciResultB1.redSha === ciResult.redSha;
13287
+ process.stderr.write(sameRed
13288
+ ? `✗ B1: the ${tableDoor} admitted this branch in the precondition table, then refused twice on the re-check at the same ${target}@${shortSha(ciResult.redSha)} — aborting before merge. Nothing pushed. (${ciResultB1.detail})\n`
13289
+ : `✗ B1: CI for ${target} is no longer green — aborting before merge. Nothing pushed. (${ciResultB1.detail})\n`);
11955
13290
  return 1;
11956
13291
  }
11957
13292
  if (ciResultB1.cureVerdict && ciResultB1.cureVerdict.ok) {
@@ -12321,7 +13656,8 @@ function cmdShip(argv) {
12321
13656
  // last — see warnDeferred's own comment for why this is scoped to exactly this window. The
12322
13657
  // window itself now OPENS at the push (e2, #304), not here: post-ship's warnings belong in the
12323
13658
  // same block, and re-assigning the collector here would silently discard them.
12324
- shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts });
13659
+ shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts,
13660
+ evidenceExtra: opts.humanDoorEvidence || '' }); // #525
12325
13661
 
12326
13662
  print('');
12327
13663
  print(`✓ Shipped ${sess.branch} → ${target} @ ${sha}${sess.issues.length ? ' (' + sess.issues.map((n) => '#' + n).join(' ') + ')' : ''}`);
@@ -12412,12 +13748,16 @@ function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, re
12412
13748
  // its last member.
12413
13749
  if (gh) {
12414
13750
  for (const gl of groupLabelsCarried) {
12415
- const openMembers = git.ghIssueListByLabel(repoAbs, gl, 'open', ['number']);
12416
- if (openMembers === null) { warn(`could not check membership of ${gl} — left in place`); continue; }
12417
- if (openMembers.length > 0) continue; // still binds the remainder — leave it
12418
- const del = git.ghLabelDelete(repoAbs, gl);
12419
- if (del.ok) print(` deleted spent group label ${gl} (every member now closed)`);
12420
- else warn(`could not delete spent group label ${gl}: ${del.stderr || 'gh label delete failed'}`);
13751
+ // #448: search says zero → a non-search read must agree before the repo-wide delete.
13752
+ const t = groupLabels.teardownSpentGroupLabel(gl, {
13753
+ searchOpen: (name) => git.ghIssueListByLabel(repoAbs, name, 'open', ['number']),
13754
+ confirmOpen: (name) => git.ghOpenIssueNumbersByLabel(repoAbs, name),
13755
+ deleteLabel: (name) => git.ghLabelDelete(repoAbs, name),
13756
+ });
13757
+ if (t.reason === 'open') continue; // still binds the remainder — leave it
13758
+ if (t.action === 'keep') { warn(groupLabels.keptReason(gl, t)); continue; }
13759
+ if (t.deleted) print(` deleted spent group label ${gl} (every member now closed)`);
13760
+ else warn(`could not delete spent group label ${gl}: ${t.error}`);
12421
13761
  }
12422
13762
  }
12423
13763
 
@@ -12800,9 +14140,28 @@ function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opt
12800
14140
  const headNow = git.git(['rev-parse', 'HEAD'], repoAbs).stdout;
12801
14141
  if (headNow === head) git.git(['reset', '--hard', preMergeSha], repoAbs); // #322: our own merge, put back
12802
14142
  release();
12803
- print(`⏸ ship-batch: trunk moved during land (${git.gitFailureLine(push.stderr)}) — nothing landed; ${trunk} rolled back to ${shortSha(preMergeSha)}.`);
12804
- print(' Run this command again: it sees the moved trunk and rebuilds the batch on it.');
12805
- return 3;
14143
+ // #509: a failed push is not proof trunk moved — re-read the remote trunk before saying so.
14144
+ const ls = git.run('git', ['ls-remote', remote, `refs/heads/${trunk}`], { cwd: repoAbs, timeoutMs: 60_000 });
14145
+ const remoteNow = ls.ok ? ((ls.stdout || '').split('\n')[0] || '').split('\t')[0].trim() : null;
14146
+ const why = shipBatch.landPushFailure({ stderr: push.stderr, remoteNow, base });
14147
+ const rolled = `nothing landed; ${trunk} rolled back to ${shortSha(preMergeSha)}`;
14148
+ const echo = () => { for (const l of why.lines) print(` │ ${l}`); };
14149
+ if (why.kind === 'trunk-moved') {
14150
+ print(`⏸ ship-batch: trunk moved during land (${remote}/${trunk} ${shortSha(base)} → ${shortSha(remoteNow)}) — ${rolled}.`);
14151
+ print(' Run this command again: it sees the moved trunk and rebuilds the batch on it.');
14152
+ } else if (why.kind === 'unreachable') {
14153
+ print(`⏸ ship-batch: the push failed and ${remote}/${trunk} could not be re-read to say why — ${rolled}. The push said:`);
14154
+ echo();
14155
+ print(` Run this command again once ${remote} answers; it re-reads trunk before deciding anything.`);
14156
+ } else {
14157
+ const who = why.kind === 'remote-rejected'
14158
+ ? `${remote} rejected the update`
14159
+ : 'the push was refused before it reached the remote (a local pre-push hook?)';
14160
+ print(`✗ ship-batch: ${who} — ${remote}/${trunk} did NOT move (still ${shortSha(base)}); ${rolled}. The push said:`);
14161
+ echo();
14162
+ print(' This is not a moved trunk: re-running hits the same refusal. Fix what the output above names, then run this command again.');
14163
+ }
14164
+ return why.exit;
12806
14165
  }
12807
14166
  print(' pushed.');
12808
14167
  deferredCollector = [];
@@ -12887,6 +14246,262 @@ function shipBatchMemberTail({ repoAbs, doc, trunk, sess, sha, closeIssues, refs
12887
14246
  // decides and deletes is one bug away from deleting on an `unknown`.
12888
14247
  // ---------------------------------------------------------------------------
12889
14248
 
14249
+ // trunk-ci — the trunk-CI verdict `colab ship` computes, read-only (#463). code-triage's §0 "red
14250
+ // trunk nobody owns" check and §5's "Trunk CI is alive" bullet call this instead of keeping a
14251
+ // `gh run list` filter of their own — two rules for one question disagreed, and the red went
14252
+ // unowned (a sha with CI green and a release workflow red read GREEN to triage, not-green to ship).
14253
+ const TRUNK_CI_TTL_DEFAULT_SEC = 45;
14254
+ const HELP_TRUNK_CI = `colab trunk-ci [--repo <path>] [--fresh] [--json]
14255
+
14256
+ Print the trunk-CI verdict \`colab ship\` would compute for the trunk's CURRENT remote head —
14257
+ the same read (shipCiCheck's readCiVerdict): by branch, re-read by commit when empty, runs from
14258
+ workflows the repo does not own dropped (#451), each workflow judged by its newest run (#461).
14259
+ Read-only: no claim, no label, no write.
14260
+
14261
+ Only runs that VERIFY the code are judged (#503): push / pull_request / merge_group triggered.
14262
+ A run of any other trigger at the same sha — a workflow_run release (release-auto.yml), a
14263
+ scheduled finalize, a dispatch, a deploy — comes after the verdict and is set aside and named in
14264
+ the detail (--json: setAside). Override in .github/project.yml, by workflow name:
14265
+ ship-gate-workflows: [CI] exactly these workflows count, whatever their trigger
14266
+ ship-ignore-workflows: [Deploy] set these aside too, even when push-triggered
14267
+
14268
+ The first output word is one verdict:
14269
+ GREEN every judged workflow's newest run at the sha succeeded — ship's row would pass
14270
+ RED a judged run completed and did not succeed — trunk is red
14271
+ PENDING a judged run is still in flight (or the sha is minutes old with no run yet)
14272
+ WEDGED a run that will never move on its own (zero jobs / hours unmoving, #155)
14273
+ NONE no repo-owned run exists at the sha — CI not wired or never started
14274
+ UNREADABLE gh unusable or the read failed — never "green"
14275
+
14276
+ Exemption doors (the cure rule, a ci-grant) are NOT applied: they let one branch past a red
14277
+ trunk, they do not make the trunk green, and the red still needs an owner.
14278
+
14279
+ A GREEN whose suite the CI guard skipped because a green run of the same workflow already
14280
+ passed an identical tree (#493) names that run in its detail ("relied on <url>"). If the cited
14281
+ head is local and its tree differs from trunk's, the read is RED: trunk is untested.
14282
+
14283
+ Cost (#495): one REST read of the runs at the sha (\`actions/runs?head_sha=\`), plus one
14284
+ check-runs read on a GREEN. No auth probe in front of it — the read is the probe, and an
14285
+ UNREADABLE explains which credential/remote condition failed. The verdict is cached per
14286
+ trunk+sha for ${TRUNK_CI_TTL_DEFAULT_SEC}s in the repo's git dir, shared by every session on the
14287
+ checkout (COLAB_TRUNK_CI_TTL=<sec> overrides, 0 disables; --fresh skips the cache for one read).
14288
+ To WAIT for CI, use \`colab ci-wait\` — never a loop around this command.
14289
+
14290
+ --fresh ignore a cached verdict (still refreshes the cache)
14291
+ --json { verdict, sha, ok, class, detail, trunk[, cited: [<run url>…] on a #493 skip][, cachedAgeSec] }
14292
+ Exit 0 whenever a verdict was read (whatever it is); 2 on UNREADABLE.`;
14293
+
14294
+ /** Map readCiVerdict's result to the closed trunk-ci vocabulary. Pure — exported for tests. */
14295
+ function trunkCiToken(r) {
14296
+ if (!r || !r.run) return 'UNREADABLE';
14297
+ if (r.verdict.ok) return 'GREEN';
14298
+ const st = r.run.status;
14299
+ if (st === 'none') return r.verdict.class === SELF_CLEARING ? 'PENDING' : 'NONE';
14300
+ if (st === 'completed') return 'RED';
14301
+ return r.verdict.class === HUMAN_GATED ? 'WEDGED' : 'PENDING';
14302
+ }
14303
+
14304
+ function cmdTrunkCi(argv) {
14305
+ const opts = parseArgs(argv, {
14306
+ values: { '--repo': 'repo' },
14307
+ flags: { '--json': 'json', '--fresh': 'fresh', '-h': 'help', '--help': 'help' },
14308
+ });
14309
+ if (opts.help) return print(HELP_TRUNK_CI);
14310
+ const repoAbs = resolveRepo(opts);
14311
+ if (!git.repoRoot(repoAbs)) throw new UserError(`${repoAbs} is not a git repo`);
14312
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
14313
+ if (!trunk) throw new UserError('cannot resolve trunk — no `trunk:` in .github/project.yml and no origin/HEAD');
14314
+
14315
+ // #495: the cache key is the trunk's CURRENT remote head — read with `git ls-remote`, which is the
14316
+ // git protocol, not the REST quota — so a new push is never answered from an older sha's verdict.
14317
+ const cache = trunkCiCache(repoAbs);
14318
+ const headSha = remoteHeadSha(repoAbs, trunk);
14319
+ const key = headSha ? `${trunk}@${headSha}` : null;
14320
+ let out = key && !opts.fresh ? cache.get(key) : null;
14321
+ if (!out) {
14322
+ // #495: no `gh auth status` probe in front of the read (it costs a REST + a GraphQL call per
14323
+ // process, and trunk-ci runs as a fresh process each time). The read itself proves the credential;
14324
+ // only an UNREADABLE pays for the explanation.
14325
+ const gh = git.ghInstalled() && !!git.remoteUrl(repoAbs);
14326
+ const r = readCiVerdict(repoAbs, gh, trunk, trunk);
14327
+ const verdict = trunkCiToken(r);
14328
+ const sha = r.run ? r.run.sha || null : null;
14329
+ let detail = r.verdict.detail;
14330
+ if (verdict === 'UNREADABLE' && gh && !git.ghState().ok) detail += ` (${ghUnusableWhy(repoAbs)})`;
14331
+ out = { verdict, trunk, sha, ok: r.verdict.ok, class: r.verdict.class || null, detail,
14332
+ ...(r.verdict.treeGreen ? { cited: r.verdict.treeGreen } : {}),
14333
+ ...(r.run && Array.isArray(r.run.setAside) && r.run.setAside.length ? { setAside: r.run.setAside } : {}) };
14334
+ if (key && verdict !== 'UNREADABLE' && sha === headSha) cache.put(key, out);
14335
+ }
14336
+ if (opts.json) {
14337
+ print(JSON.stringify(out, null, 2));
14338
+ } else {
14339
+ const age = out.cachedAgeSec !== undefined ? ` (cached ${out.cachedAgeSec}s ago)` : '';
14340
+ print(`${out.verdict} ${trunk}${out.sha ? `@${shortSha(out.sha)}` : ''} — ${out.detail}${age}`);
14341
+ }
14342
+ return out.verdict === 'UNREADABLE' ? 2 : 0;
14343
+ }
14344
+
14345
+ /** `git ls-remote <remote> refs/heads/<branch>` → sha, or null. Git protocol — no REST quota. */
14346
+ function remoteHeadSha(repoAbs, branch) {
14347
+ const remote = git.remoteInfo(repoAbs).name || 'origin';
14348
+ const r = git.git(['ls-remote', remote, `refs/heads/${branch}`], repoAbs);
14349
+ if (!r.ok) return null;
14350
+ return (r.stdout.split('\n')[0] || '').split('\t')[0].trim() || null;
14351
+ }
14352
+
14353
+ /**
14354
+ * #495: the trunk-ci verdict cache — `<git common dir>/colab-trunk-ci.json`, so every session and
14355
+ * worktree on one checkout shares it. Keyed by `<trunk>@<sha>`; an entry older than the TTL is a
14356
+ * miss. Best effort both ways: an unreadable/unwritable file is simply no cache.
14357
+ */
14358
+ function trunkCiCache(repoAbs) {
14359
+ const env = process.env.COLAB_TRUNK_CI_TTL;
14360
+ const ttl = env !== undefined && env !== '' && Number.isFinite(Number(env)) ? Number(env) : TRUNK_CI_TTL_DEFAULT_SEC;
14361
+ const dir = git.git(['rev-parse', '--path-format=absolute', '--git-common-dir'], repoAbs);
14362
+ const file = dir.ok && dir.stdout ? path.join(dir.stdout.trim(), 'colab-trunk-ci.json') : null;
14363
+ const load = () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')) || {}; } catch (_) { return {}; } };
14364
+ return {
14365
+ get(key) {
14366
+ if (!file || ttl <= 0) return null;
14367
+ const e = load()[key];
14368
+ if (!e || !e.at || !e.out) return null;
14369
+ const age = Math.floor((Date.now() - e.at) / 1000);
14370
+ return age >= 0 && age < ttl ? { ...e.out, cachedAgeSec: age } : null;
14371
+ },
14372
+ put(key, out) {
14373
+ if (!file || ttl <= 0) return;
14374
+ const now = Date.now();
14375
+ const all = load();
14376
+ for (const k of Object.keys(all)) if (!all[k] || now - all[k].at > ttl * 1000) delete all[k];
14377
+ all[key] = { at: now, out };
14378
+ try {
14379
+ const tmp = `${file}.${process.pid}.tmp`;
14380
+ fs.writeFileSync(tmp, JSON.stringify(all));
14381
+ fs.renameSync(tmp, file);
14382
+ } catch (_) { /* no cache, not an error */ }
14383
+ },
14384
+ };
14385
+ }
14386
+
14387
+ // ci-wait — THE way to wait for CI (#495). Agents' hand-rolled `sleep N; gh run …` loops spent ~88%
14388
+ // of a shared identity's REST quota in one measured hour; this waits with backoff, conditional
14389
+ // requests, a deadline, and a distinct exit code for every way a wait can end.
14390
+ const HELP_CI_WAIT = `colab ci-wait <run-id> | --sha <sha> [--branch <b>] [--repo <path>] [--timeout <dur>] [--json]
14391
+
14392
+ Wait for CI and exit with its outcome. The ONE way to wait for a run: never hand-roll a
14393
+ \`sleep N; gh run view\` loop, never run two waits for the same run, never hide gh's stderr.
14394
+
14395
+ <run-id> wait for one workflow run (actions/runs/<id>)
14396
+ --sha <sha> wait for EVERY repo-owned workflow at the sha (the verdict colab ship reads:
14397
+ newest run per workflow, dynamic workflows dropped — #451/#461; only runs that
14398
+ verify the code, so a post-CI release/deploy run is set aside — #503); a sha
14399
+ with no run yet counts as pending until the deadline. An abbreviated sha is
14400
+ resolved in the repo first, and refused (exit 2) when it does not resolve — #529
14401
+ --branch <b> narrow --sha to runs on that branch
14402
+ --timeout <d> deadline: 45m (default), 90s, 1h, or seconds
14403
+
14404
+ Polls at 0s, then +30s, +60s, +120s, +120s … until the deadline. Every poll after the first is a
14405
+ conditional request (If-None-Match); a 304 is not counted against the REST rate limit. After two
14406
+ 304s in a row, and on the last poll before the deadline, it re-reads unconditionally: a stale ETag
14407
+ can cost one paid call, never the whole wait (#505). A 15-minute run costs about 10 requests. One wait per run per checkout: a second waiter is refused.
14408
+
14409
+ Exit codes — branch on these, never on the text:
14410
+ 0 GREEN the run (every judged run at the sha) succeeded
14411
+ 1 RED completed and did not succeed
14412
+ 2 usage bad arguments
14413
+ 3 TIMEOUT the deadline passed while still pending
14414
+ 4 RATE_LIMITED GitHub refused for quota (403/429) — the wait ENDS, it does not retry
14415
+ 5 UNKNOWN a read failed or returned a state it cannot classify
14416
+ 6 ALREADY_WAITING another live ci-wait on this checkout holds the same run/sha
14417
+
14418
+ It prints the wait it did: outcome, elapsed time, polls, and how many were 304s.
14419
+ --json { outcome, exit, target, polls, notModified, forced, waitedSec, detail, status, conclusion, url }`;
14420
+
14421
+ function cmdCiWait(argv) {
14422
+ const opts = parseArgs(argv, {
14423
+ values: { '--repo': 'repo', '--sha': 'sha', '--branch': 'branch', '--timeout': 'timeout' },
14424
+ flags: { '--json': 'json', '-h': 'help', '--help': 'help' },
14425
+ });
14426
+ if (opts.help) return print(HELP_CI_WAIT);
14427
+ const runId = opts._ && opts._[0];
14428
+ if ((runId ? 1 : 0) + (opts.sha ? 1 : 0) !== 1 || (runId && !/^\d+$/.test(runId)) || (opts.branch && !opts.sha)) {
14429
+ warn('ci-wait takes exactly one of <run-id> (numeric) or --sha <sha> [--branch <b>]');
14430
+ return ciWait.EXIT.USAGE;
14431
+ }
14432
+ const deadlineSec = opts.timeout !== undefined ? ciWait.parseDuration(opts.timeout) : ciWait.DEFAULT_DEADLINE_SEC;
14433
+ if (!deadlineSec) { warn(`--timeout: cannot read "${opts.timeout}" (try 45m, 90s, 1h)`); return ciWait.EXIT.USAGE; }
14434
+ const repoAbs = resolveRepo(opts);
14435
+ if (opts.sha) {
14436
+ // #529: the API reports a 40-hex head_sha and the rows are matched by equality, so an
14437
+ // abbreviated --sha would match nothing and wait out the whole deadline as "pending" — on a run
14438
+ // that finished green in minutes. Resolve it here, or refuse; never poll with it.
14439
+ const full = git.fullSha(repoAbs, opts.sha);
14440
+ if (!full) {
14441
+ warn(`--sha ${opts.sha}: not a full 40-hex sha and it does not resolve to one commit in ${repoAbs} — pass the full sha (\`git rev-parse <sha>\`), or fetch first`);
14442
+ return ciWait.EXIT.USAGE;
14443
+ }
14444
+ opts.sha = full;
14445
+ }
14446
+ if (!git.ghInstalled()) { warn('gh is not installed — cannot read CI'); return ciWait.EXIT.UNKNOWN; }
14447
+
14448
+ const target = runId ? `run ${runId}` : `sha ${shortSha(opts.sha)}${opts.branch ? ` on ${opts.branch}` : ''}`;
14449
+ const apiPath = runId
14450
+ ? `repos/{owner}/{repo}/actions/runs/${runId}`
14451
+ : `repos/{owner}/{repo}/actions/runs?head_sha=${encodeURIComponent(opts.sha)}${opts.branch ? `&branch=${encodeURIComponent(opts.branch)}` : ''}&per_page=100`;
14452
+
14453
+ const gitDir = git.git(['rev-parse', '--path-format=absolute', '--git-common-dir'], repoAbs);
14454
+ const lock = gitDir.ok ? ciWait.acquireLock(path.join(gitDir.stdout.trim(), 'colab-ci-wait'), runId || `${opts.sha}-${opts.branch || ''}`) : { ok: true, release: () => {} };
14455
+ if (!lock.ok) {
14456
+ warn(`another ci-wait (pid ${lock.holder}) is already waiting on ${target} in this checkout — read its result, do not start a second wait`);
14457
+ return ciWait.EXIT.ALREADY_WAITING;
14458
+ }
14459
+
14460
+ const verifyPolicy = verifyRuns.parsePolicy(projectDoc(repoAbs));
14461
+ const poll = (etag) => {
14462
+ const r = git.ghApiConditional(repoAbs, apiPath, etag);
14463
+ if (r.kind !== 'ok') return r;
14464
+ let summary;
14465
+ if (runId) {
14466
+ summary = { status: r.json.status, conclusion: r.json.conclusion || null, url: r.json.html_url || null };
14467
+ } else {
14468
+ const rows = Array.isArray(r.json.workflow_runs) ? r.json.workflow_runs.map(ciWait.restRow).filter((x) => x.headSha === opts.sha) : null;
14469
+ if (!rows) return { kind: 'error', status: r.status, detail: 'response has no workflow_runs' };
14470
+ // #503: the same verifying-runs policy ship reads — a wait on trunk's head ends when the CI
14471
+ // that verifies the code ends, not when the post-CI release run does.
14472
+ summary = git.summarizeRunsForCommit(rows, opts.sha, { verifying: verifyPolicy });
14473
+ const pick = rows.find((x) => x.databaseId === summary.databaseId);
14474
+ summary = { ...summary, url: pick ? pick.url : null };
14475
+ }
14476
+ return { ...r, summary, state: ciWait.runState(summary) };
14477
+ };
14478
+
14479
+ if (!opts.json) process.stderr.write(`ci-wait: waiting on ${target} (deadline ${ciWait.fmtDuration(deadlineSec * 1000)}; polls at +0s, +30s, +60s, then every 120s)\n`);
14480
+ let res;
14481
+ try {
14482
+ res = ciWait.waitLoop({
14483
+ poll, sleep: ciWait.sleepSync, deadlineSec,
14484
+ onPoll: (p) => { if (!opts.json) process.stderr.write(`ci-wait: poll ${p.poll} at +${ciWait.fmtDuration(p.elapsedMs)} — ${p.state}${p.notModified ? ' (304, not counted)' : ''}${p.forced ? ' (unconditional re-read — #505)' : ''}\n`); },
14485
+ });
14486
+ } finally {
14487
+ lock.release();
14488
+ }
14489
+ const s = (res.last && res.last.summary) || {};
14490
+ const code = ciWait.EXIT[res.outcome];
14491
+ const out = {
14492
+ outcome: res.outcome, exit: code, target, polls: res.polls, notModified: res.notModified, forced: res.forced,
14493
+ waitedSec: Math.round(res.waitedMs / 1000), detail: res.detail || null,
14494
+ status: s.status || null, conclusion: s.conclusion || null, url: s.url || null,
14495
+ ...(Array.isArray(s.setAside) && s.setAside.length ? { setAside: s.setAside } : {}),
14496
+ };
14497
+ if (opts.json) print(JSON.stringify(out, null, 2));
14498
+ else {
14499
+ print(`${res.outcome} ${target} — waited ${ciWait.fmtDuration(res.waitedMs)}, ${res.polls} poll(s), ${res.notModified} of them 304` +
14500
+ `${s.status ? ` · ${s.status}${s.conclusion ? `/${s.conclusion}` : ''}` : ''}${s.url ? ` · ${s.url}` : ''}${res.detail ? ` — ${res.detail}` : ''}${verifyRuns.setAsideNote(s.setAside)}`);
14501
+ }
14502
+ return code;
14503
+ }
14504
+
12890
14505
  const HELP_LANDED = `colab landed [--repo <path>] [--worktree <name> | --branch <br>] [--base <br>] [--all] [--json]
12891
14506
 
12892
14507
  Has this branch's work already landed on its base? The shared answer behind code-sweep's buckets
@@ -13230,11 +14845,12 @@ function cmdDeliver(argv) {
13230
14845
  if (!tip || !ownerTip) return fail(`${remote}/${trunk} or ${remote}/${owner.branch} does not resolve after the fetch`);
13231
14846
 
13232
14847
  // 2. every delivery PR, any state
13233
- const r = git.run('gh', ['pr', 'list', '--base', owner.branch, '--head', trunk, '--state', 'all', '--limit', '50',
13234
- '--json', 'number,url,state,mergedAt,headRefOid,title'], { cwd: repoAbs });
14848
+ const r = tracker.forRepo(repoAbs).prList({
14849
+ base: owner.branch, head: trunk, state: 'all', limit: 50, fields: ['number', 'url', 'state', 'mergedAt', 'headRefOid', 'title'],
14850
+ });
13235
14851
  if (!r.ok) return fail(`could not list pull requests: ${(r.stderr || '').split('\n')[0]}`);
13236
- let list;
13237
- try { list = JSON.parse(r.stdout || '[]'); } catch (_) { return fail('gh pr list returned unparseable JSON'); }
14852
+ const list = r.stdout ? r.data : []; // an empty reply is no PRs here, as it always was
14853
+ if (list === null) return fail('gh pr list returned unparseable JSON');
13238
14854
  const prs = ownerBranch.classifyPrs(list);
13239
14855
 
13240
14856
  // 3. the undelivered range: since the last merged delivery's head when that head is still on
@@ -13286,7 +14902,7 @@ function cmdDeliver(argv) {
13286
14902
  return 1;
13287
14903
  }
13288
14904
  if (d.action === 'refresh') {
13289
- const e = git.run('gh', ['pr', 'edit', String(prs.open.number), '--title', text.title, '--body', text.body], { cwd: repoAbs });
14905
+ const e = tracker.forRepo(repoAbs).prEdit(prs.open.number, { title: text.title, body: text.body });
13290
14906
  if (!e.ok) return fail(`could not refresh PR #${prs.open.number}: ${(e.stderr || '').split('\n')[0]}`);
13291
14907
  out.done = `refreshed PR #${prs.open.number} (${prs.open.url || ''}) — waiting on the owner`;
13292
14908
  } else {
@@ -13695,7 +15311,7 @@ Commands:
13695
15311
  migration-grant <issue> --branch B | --revoke | --list [--json] human-only ship migration exemption (#98)
13696
15312
  decision <issue> --record --ruled-by N | --reopen --ruled-by N | --list [--json]
13697
15313
  record/reopen a needs-decision answer (#121, #122)
13698
- ci-grant <issue> --branch B | --revoke | --list [--json] human-only ship trunk-CI-green exemption (#105)
15314
+ ci-grant <issue> --branch B | --revoke | --list [--json] ship trunk-CI-green exemption: human, or ci-reviewer under opt-in (#105, #504)
13699
15315
  claims [--json] [--sync] list / reconcile with GitHub
13700
15316
 
13701
15317
  port alloc [--count N] [--range A-B] [--worktree N|--claim I|--label S]
@@ -13710,6 +15326,12 @@ Commands:
13710
15326
  code-wrap Phase B → the branch's recorded base (trunk, or a
13711
15327
  declared line). --json (--dry only): machine-readable
13712
15328
  preconditions with a closed refusal-class vocabulary (#77)
15329
+ trunk-ci [--fresh] [--json] the trunk-CI verdict ship computes, read-only (#463):
15330
+ GREEN | RED | PENDING | WEDGED | NONE | UNREADABLE
15331
+ (cached per sha ~45s in .git — #495)
15332
+ ci-wait <run-id> | --sha S [--branch B] [--timeout D] [--json]
15333
+ WAIT for CI with backoff + conditional requests (#495);
15334
+ exit 0 green · 1 red · 3 timeout · 4 rate-limited · 5 unknown
13713
15335
  landed [--worktree N | --branch B | --all] [--base B] [--json] has this work already landed?
13714
15336
  (the shared rule behind code-sweep's buckets — correct
13715
15337
  across squash merges, where "commits ahead" is not)
@@ -13797,6 +15419,8 @@ function main(argv) {
13797
15419
  case 'worktrees': return cmdWorktrees(rest);
13798
15420
  case 'ship': return cmdShip(rest);
13799
15421
  case 'landed': return cmdLanded(rest);
15422
+ case 'trunk-ci': return cmdTrunkCi(rest);
15423
+ case 'ci-wait': return cmdCiWait(rest);
13800
15424
  case 'holders': return cmdHolders(rest);
13801
15425
  case 'promote': return cmdPromote(rest);
13802
15426
  case 'deliver': return cmdDeliver(rest);