@futurelastic/colab-handbook 1.12.0 → 1.13.0-rc.1

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 (73) hide show
  1. package/README.md +243 -213
  2. package/README.vi.md +246 -186
  3. package/audit/audit.mjs +193 -10
  4. package/package.json +6 -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 +1691 -254
  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 +203 -0
  23. package/tools/lib/claim-comments.js +13 -64
  24. package/tools/lib/claim-identity.js +4 -7
  25. package/tools/lib/codec/claim.d.ts +41 -0
  26. package/tools/lib/codec/claim.js +151 -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 +716 -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 +762 -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 +303 -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 +106 -0
  63. package/tools/lib/ship-batch.js +36 -1
  64. package/tools/lib/stamp.js +7 -0
  65. package/tools/lib/tracker-fake.js +195 -0
  66. package/tools/lib/tracker-github.js +106 -0
  67. package/tools/lib/tracker-scenarios.json +206 -0
  68. package/tools/lib/tracker.js +64 -0
  69. package/tools/lib/tree-green.js +88 -0
  70. package/tools/lib/util.js +17 -1
  71. package/tools/lib/verify-runs.js +104 -0
  72. package/tools/lib/wake.js +8 -90
  73. 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');
@@ -129,7 +135,8 @@ function resolveRepo(opts) {
129
135
  * `.github/project.yml` into the main checkout when run from inside a worktree it was supposed
130
136
  * to target — silently violating "the main checkout stays on trunk at rest" (#258). This
131
137
  * 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.
138
+ * once used at most other cmd* call sites (normalised since #487 — resolveRepoOrCwd), as a named,
139
+ * reusable resolver for the one question that genuinely wants the caller's own tree.
133
140
  */
134
141
  function resolveWorkingRepo(opts) {
135
142
  let r = opts.repo;
@@ -154,16 +161,60 @@ function knownRepos(config) {
154
161
  return extra;
155
162
  }
156
163
 
157
- /** Find a single claim by issue number, optionally constrained to a repo. */
164
+ /**
165
+ * The repo a lookup with no --repo is about: --repo (normalised) or the MAIN root of cwd, or null.
166
+ *
167
+ * #487: this used to be spelled `resolveRepoOrCwd(opts)`
168
+ * at a dozen call sites — normalised with --repo, NOT normalised without it. Run from inside a
169
+ * linked worktree, the bare form answered with the worktree's own root, so a release looked up
170
+ * `<worktree>#N` while the claim sat under `<mainRoot>#N`. Every one of those sites is about repo
171
+ * STATE or the tracker (claims, ports, grants, events), never a committable file — for that,
172
+ * resolveWorkingRepo() is the deliberate exception.
173
+ */
174
+ function resolveRepoOrCwd(opts) {
175
+ return opts.repo ? resolveRepo(opts) : (git.mainRepoRoot(process.cwd()) || null);
176
+ }
177
+
178
+ /**
179
+ * The main checkout a claim row belongs to, given the path in its key (or its `repo` field).
180
+ *
181
+ * #487: an older writer (`claims --sync` run from inside a linked worktree) keyed rows by the
182
+ * WORKTREE's path. Those rows outlive the worktree, and the path no longer exists, so nothing could
183
+ * resolve it back to its repo — `release` missed them with and without --repo, forever. A path that
184
+ * exists resolves through git; a vanished one is attributed to the nearest existing ancestor's main
185
+ * root, but only when that ancestor IS a repo the path sits inside — never a guess across repos.
186
+ */
187
+ function claimHomeRoot(p) {
188
+ if (!p) return p;
189
+ if (fs.existsSync(p)) return git.mainRepoRoot(p) || p;
190
+ let dir = path.dirname(p);
191
+ while (dir && dir !== path.dirname(dir) && !fs.existsSync(dir)) dir = path.dirname(dir);
192
+ const root = dir && fs.existsSync(dir) ? git.mainRepoRoot(dir) : null;
193
+ return root && p.startsWith(`${root}${path.sep}`) ? root : p;
194
+ }
195
+
196
+ /** Does the claim key `k` belong to `repoAbs` (a main root)? Includes legacy worktree-keyed rows (#487). */
197
+ function claimKeyInRepo(k, repoAbs) {
198
+ if (k.startsWith(`${repoAbs}#`)) return true;
199
+ const keyPath = k.slice(0, k.lastIndexOf('#'));
200
+ return keyPath.startsWith(`${repoAbs}${path.sep}`) && claimHomeRoot(keyPath) === repoAbs;
201
+ }
202
+
203
+ /**
204
+ * Find a single claim by issue number, optionally constrained to a repo. `repo` in the result is
205
+ * the claim's MAIN root — for a legacy worktree-keyed row (#487) that is not `claim.repo`, which
206
+ * names a directory that may no longer exist; anything talking to the tracker must use `repo`.
207
+ */
158
208
  function findClaim(st, num, repoAbs) {
159
209
  const matches = Object.entries(st.claims).filter(([, c]) => normIssueNum(c.issue) === num);
160
- const scoped = repoAbs ? matches.filter(([k]) => k.startsWith(`${repoAbs}#`)) : matches;
210
+ const scoped = repoAbs ? matches.filter(([k]) => claimKeyInRepo(k, repoAbs)) : matches;
161
211
  if (scoped.length === 0) return null;
162
212
  if (scoped.length > 1) {
163
- const repos = scoped.map(([k]) => shortRepo(k.split('#')[0])).join(', ');
213
+ const repos = scoped.map(([k]) => shortRepo(k.slice(0, k.lastIndexOf('#')))).join(', ');
164
214
  throw new UserError(`Issue #${num} is claimed in multiple repos (${repos}) — disambiguate with --repo`);
165
215
  }
166
- return { key: scoped[0][0], claim: scoped[0][1] };
216
+ const [key, claim] = scoped[0];
217
+ return { key, claim, repo: repoAbs || claimHomeRoot(claim.repo || key.slice(0, key.lastIndexOf('#'))) };
167
218
  }
168
219
 
169
220
  function isGhUsable(repoAbs) {
@@ -177,7 +228,12 @@ function isGhUsable(repoAbs) {
177
228
  */
178
229
  function ghUnusableWhy(repoAbs) {
179
230
  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';
231
+ if (!s.ok && s.reason === 'missing') return 'gh is not installed';
232
+ if (!s.ok && s.reason === 'rate-limited') { // #516
233
+ const until = s.resetAt ? ` until ${new Date(s.resetAt).toISOString().replace(/\.\d{3}Z$/, 'Z')}` : '';
234
+ return `gh credential is rate-limited${until} — not a credential problem: wait for the reset, or switch account`;
235
+ }
236
+ if (!s.ok) return 'gh has no working credential — `gh api user` fails';
181
237
  const rp = git.remoteProblem(git.remoteInfo(repoAbs)); // #301: ambiguous remotes / a broken colab.remote
182
238
  if (rp) return rp;
183
239
  if (!git.remoteUrl(repoAbs)) return 'no origin remote';
@@ -195,9 +251,10 @@ function ghUnusableWhy(repoAbs) {
195
251
  // GitHub offers no atomic check-and-set on labels/assignees.
196
252
  // ---------------------------------------------------------------------------
197
253
 
198
- // The claim/release comment markers and parsers live in tools/lib/claim-comments.js (#369/#375) —
254
+ // The claim/release comment markers and their encode/decode pairs live in tools/lib/codec/claim.js
255
+ // (#497); the readers built on them (liveness, tie-break) in tools/lib/claim-comments.js (#369/#375) —
199
256
  // 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;
257
+ const { liveClaimComments, tieBreakVerdict } = claimComments; // the format itself: codec/claim.js (#497)
201
258
 
202
259
  /**
203
260
  * #369: may a comment colab posts to THIS repo's tracker name the host in its `host` field? The
@@ -388,14 +445,6 @@ function identityLegend(entries) {
388
445
  print(' Repair: colab worktree tag <worktree> --session <url>');
389
446
  }
390
447
 
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
448
  /**
400
449
  * Worktree lifecycle status, backfilled-on-read: entries created before this field existed (or by
401
450
  * an older colab) render as `running`. Values: `running` (default, at create) → `merged` (branch
@@ -404,17 +453,18 @@ function sessionCommentSuffix(session, sessionName) {
404
453
  */
405
454
  function wtStatus(wt) { return (wt && wt.status) || 'running'; }
406
455
 
407
- /** The exact claim-comment body. Keep in lockstep with CLAIM_RE/parseSessionField and the README. */
456
+ /**
457
+ * The exact claim-comment body. The format itself is codec/claim.js `encodeClaim` (#497); this
458
+ * supplies what the codec deliberately does not hold — the clock and the machine digest. `-` stands
459
+ * for "no branch"/"no worktree" (#53, it used to be the word `trunk`). `host` is the raw hostname
460
+ * where the destination may name it, the `h:` token where it may not (#369, `commentHost`); the
461
+ * comparable identity is the machine digest beside it (#327), omitted when no id resolved.
462
+ */
408
463
  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);
464
+ return codec.encodeClaim({
465
+ worktree: wtName, branch, host, at: nowISO(),
466
+ machine: machine.machineToken(myMachineId()) || '', session, sessionName,
467
+ });
418
468
  }
419
469
 
420
470
  /** Issues whose EXISTING local claim sits on a different worktree than the one we're claiming onto. */
@@ -470,9 +520,14 @@ function remoteClaimConflicts(st, repoAbs, nums) {
470
520
  const want = new Set(nums);
471
521
  const records = [...Object.values(st.worktrees || {}), ...Object.values(st.claims || {})];
472
522
  const ours = (b) => records.some((r) => r && r.repo === repoAbs && r.branch === b && machine.isLocal(r));
523
+ // #485: a dependabot ref, trunk and every declared integration: line are never a session's claim —
524
+ // their trailing digits are a version or an accident of naming. Same filter as code-sweep §1.3.
525
+ const doc = projectDoc(repoAbs);
526
+ const trunk = resolveTrunk(repoAbs, doc) || '';
527
+ const scope = { trunk, integration: trunk ? resolveIntegration(repoAbs, doc, trunk) : [] };
473
528
  const conflicts = [];
474
529
  for (const h of heads.heads) {
475
- const carried = shipguard.branchIssueNumbers(h.branch).filter((n) => want.has(n));
530
+ const carried = branchName.claimIssueNumbers(h.branch, scope).filter((n) => want.has(n));
476
531
  if (!carried.length || ours(h.branch)) continue;
477
532
  for (const num of carried) conflicts.push({ num, remote, branch: h.branch, sha: h.sha });
478
533
  }
@@ -663,7 +718,7 @@ function postClaimComment(repoAbs, num, wtName, branch, session, sessionName) {
663
718
  function postReleaseComment(repoAbs, num) {
664
719
  const info = git.ghIssueView(repoAbs, num, ['state']);
665
720
  if (info && info.state === 'CLOSED') return true; // don't chatter on a closed issue
666
- const r = git.ghIssueComment(repoAbs, num, RELEASE_MARK);
721
+ const r = git.ghIssueComment(repoAbs, num, codec.encodeRelease());
667
722
  if (!r.ok) { warnDeferred(`could not post release comment on #${num} (${r.stderr.split('\n')[0] || r.code})`); return false; }
668
723
  return true;
669
724
  }
@@ -1208,8 +1263,8 @@ Refuses, naming each failed condition (all are reported, not just the first):
1208
1263
  switch-dependencies a colab:switch marker is malformed, or a finished switch needs one that is not
1209
1264
  manifest-version the tag does not equal the version a manifest declares (VERSION, package.json,
1210
1265
  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
1266
+ passes: the tag is the version (#424). Under release.version-source: tag (#438;
1267
+ the default where the machine cuts the tag, #484) a differing manifest is DERIVABLE — skipped, named in the tag message, and
1213
1268
  stamped from the tag by the repo's own release step (never on trunk)
1214
1269
  on-trunk the commit is not an ancestor of main, or the checkout is shallow (#424)
1215
1270
  outranks-final the version is not strictly greater than the highest final tag (#424)
@@ -1235,6 +1290,20 @@ Refuses, naming each failed condition (all are reported, not just the first):
1235
1290
  There the bump reads the promoted commits (main's merge subject is skipped),
1236
1291
  and a switch-removal child counts when its Closes #N was promoted.
1237
1292
 
1293
+ Route deploy-tag-fast (#446) — a deploy: tag repo with the operator's grant and a declared health gate:
1294
+ --auto tags the FINAL vX.Y.Z on main's green head — no candidate, no test period — publishes it as
1295
+ the latest GitHub Release, moves the stable channel, and prints final/deploy in --json so the
1296
+ release workflow's deploy job deploys it in the same run. Without --auto it refuses: a final cut by
1297
+ hand would reach production with no deploy job behind it. Five more conditions there:
1298
+ spacing release.final-spacing (default and floor 1h) since the newest final — inside
1299
+ it the run is a NO-OP; the first run after it tags main's head
1300
+ already-final main's head already carries a final — a NO-OP
1301
+ final-grant release.final-grant's decision still resolves (recorded, trusted, not reopened)
1302
+ release-hold an open issue carries the release-hold label (a human veto)
1303
+ migration-grant a migration since the last final with no grant on the version's tracking
1304
+ issue — refused; a non-dry run opens "release: vX.Y.Z" if needed and posts the
1305
+ one human command (COLAB_HUMAN=1 colab migration-grant <N> --branch vX.Y.Z)
1306
+
1238
1307
  The bump (without --auto) is release-status's semverSuggestion since the last final tag (candidates skipped): fix ->
1239
1308
  patch, feat -> minor; a breaking change is a minor pre-1.0 and a refusal from 1.0 on.
1240
1309
  --bump patch|minor override the computed bump — requires --reason, which is recorded on the tag
@@ -1261,16 +1330,13 @@ no-op; 1 when refused.
1261
1330
  function readAllIssuesForSwitches(repoAbs) {
1262
1331
  const LIMIT = 5000;
1263
1332
  // 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
- }
1333
+ const r = tracker.forRepo(repoAbs).issueListAll({
1334
+ limit: LIMIT, fields: ['number', 'state', 'stateReason', 'body', 'title', 'labels', 'createdAt', 'closedAt', 'url'],
1335
+ maxBuffer: 512 * 1024 * 1024,
1336
+ });
1337
+ const list = r.data; // null: the read failed or was unparseable
1338
+ // A full page may be a truncated one — an unread marker is not a cleared one.
1339
+ return Array.isArray(list) && list.length < LIMIT ? list : null;
1274
1340
  }
1275
1341
 
1276
1342
  /** [{status, path, content}] for every path changed between `from` (null = the empty tree) and `sha`; null on a git failure. */
@@ -1310,7 +1376,7 @@ function measureCandidateConditions(repoAbs, { sha, lastFinal, at, readRuns, iss
1310
1376
  const why = ghUnusableWhy(repoAbs);
1311
1377
  ci = { ok: false, detail: `gh not usable (${why}) — cannot confirm CI at ${at}` };
1312
1378
  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` };
1379
+ switches = { ok: false, unread: true, detail: `gh not usable (${why}) — the colab:switch markers cannot be read` };
1314
1380
  } else {
1315
1381
  const rows = readRuns();
1316
1382
  const run = git.summarizeRunsForCommit(rows, sha);
@@ -1326,7 +1392,7 @@ function measureCandidateConditions(repoAbs, { sha, lastFinal, at, readRuns, iss
1326
1392
  const declared = migrationPaths.unionPaths(projectDoc(repoAbs), projectDocAt(repoAbs, sha));
1327
1393
  const changes = releaseCutChanges(repoAbs, lastFinal, sha, declared);
1328
1394
  const schema = changes === null
1329
- ? { ok: false, detail: 'git diff failed — schema changes cannot be read' }
1395
+ ? { ok: false, unread: true, detail: 'git diff failed — schema changes cannot be read' }
1330
1396
  : releaseCut.schemaVerdict(changes, lastFinal || 'the first commit', declared);
1331
1397
  // #441: every migration file since the last final, destructive or not — an operator-granted
1332
1398
  // automatic final refuses an ungranted one (release-finalize.js migrationGrantVerdict).
@@ -1441,6 +1507,75 @@ function measureAutoSignals(repoAbs, { doc, sha, lastFinal, remote, issues, trun
1441
1507
  return { signals, migration: (v) => releaseCut.parseMigrationSection(migrationText, v) };
1442
1508
  }
1443
1509
 
1510
+ /** #446: every final `vX.Y.Z` tag as [{ name, date }] — what release.final-spacing counts. A human's final counts too. */
1511
+ function finalTags(repoAbs) {
1512
+ const fe = git.git(['for-each-ref', 'refs/tags', '--format=%(refname:short)%09%(creatordate:iso-strict)'], repoAbs);
1513
+ return (fe.ok ? fe.stdout.split('\n').filter(Boolean) : []).map((l) => l.split('\t'))
1514
+ .filter(([name]) => releaseCut.parseVersion(name)).map(([name, date]) => ({ name, date }));
1515
+ }
1516
+
1517
+ /**
1518
+ * #446: what route deploy-tag-fast keeps in place of a test period, measured — the operator's grant
1519
+ * (the #441 reader, against trunk's trust-humans), the repo-wide release-hold veto, every migration
1520
+ * since the last final against a grant on the computed version's tracking issue, and the spacing
1521
+ * since the newest final. The version is computed here only to find that tracking issue; decide()
1522
+ * computes it again from the same inputs, so the two cannot disagree.
1523
+ */
1524
+ function measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: paths }) {
1525
+ const grantDecl = policy.effective.finalGrant;
1526
+ const trust = trustAt(repoAbs, `${remote}/main`);
1527
+ const finalGrant = isGhUsable(repoAbs)
1528
+ ? releasePolicy.finalGrantVerdict(git.ghIssueView(repoAbs, grantDecl.issue, ['state', 'labels', 'comments']), { issue: grantDecl.issue, trust })
1529
+ : { ok: false, unread: true, ruledBy: null, detail: `release.final-grant #${grantDecl.issue} could not be read: gh not usable (${ghUnusableWhy(repoAbs)})` };
1530
+ const holds = releaseCut.holdsVerdict(issues);
1531
+ let tracking = null;
1532
+ let grant = null;
1533
+ const v = auto ? releaseCut.decideAutoVersion({ lastFinal, signals: auto.signals, migration: auto.migration, tags }) : null;
1534
+ if (v && v.ok && issues) {
1535
+ const open = issues.filter((i) => String(i.state || '').toUpperCase() === 'OPEN' && releaseFinalize.parseReleaseMarker(i.body) === v.version);
1536
+ if (open.length) tracking = { number: open[0].number };
1537
+ }
1538
+ if (paths && paths.length) {
1539
+ grant = tracking
1540
+ ? migrationGrant.evaluateIssue(git.ghIssueView(repoAbs, tracking.number, ['state', 'labels', 'comments']), v.version, tracking.number, labels.MIGRATION_GRANT_LABEL, { trust })
1541
+ : { ok: false, reason: 'no tracking issue yet to carry a grant' };
1542
+ if (grant && grant.ok) grant = { ...grant, issue: tracking.number };
1543
+ }
1544
+ const migrations = { ...releaseFinalize.migrationGrantVerdict({ paths, grant, since: lastFinal }), paths: paths || null };
1545
+ const spacing = releaseCut.spacingVerdict({ finals: finalTags(repoAbs), spacingHours: policy.effective.finalSpacingHours, now: new Date().toISOString() });
1546
+ return { finalGrant, holds, migrations, spacing, tracking };
1547
+ }
1548
+
1549
+ /** Post `text` on issue `num` once — idempotent by release-finalize's event marker. */
1550
+ function commentOnce(repoAbs, num, fields, text) {
1551
+ const view = git.ghIssueView(repoAbs, num, ['comments']);
1552
+ if (view && releaseFinalize.hasEvent(view.comments, fields)) return;
1553
+ const r = git.ghIssueComment(repoAbs, num, `${releaseFinalize.eventMarker(fields)}\n${text}`);
1554
+ if (!r.ok) warn(`could not comment on #${num}: ${String(r.stderr || '').split('\n')[0]}`);
1555
+ }
1556
+
1557
+ /**
1558
+ * #426: one "Released in vX.Y.Z" comment on every issue the version carries — the closing references
1559
+ * in (previous final, sha], minus `exclude` (the release tracking issues). Idempotent by event marker.
1560
+ * Shared by `release finalize` and, on route deploy-tag-fast (#446), `release cut`.
1561
+ */
1562
+ function announceCarried(repoAbs, { tagNames, exclude, version, sha }) {
1563
+ const prev = releaseFinalize.previousFinal(tagNames, version);
1564
+ if (!prev) return { range: null, issues: [], posted: [], skipped: [], detail: 'no previous final — the first version announces nothing' };
1565
+ const log = git.git(['log', '--format=%B%x00', `${prev}..${sha}`], repoAbs);
1566
+ 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' }; }
1567
+ const nums = releaseFinalize.carriedIssues(log.stdout.split('\0'), { exclude });
1568
+ const posted = []; const skipped = [];
1569
+ for (const n of nums) {
1570
+ const view = git.ghIssueView(repoAbs, n, ['comments']);
1571
+ if (!view) { skipped.push(n); continue; }
1572
+ if (releaseFinalize.hasEvent(view.comments, releaseFinalize.releasedEvent(version))) continue;
1573
+ const r = git.ghIssueComment(repoAbs, n, releaseFinalize.releasedComment(version, sha));
1574
+ if (r.ok) posted.push(n); else { skipped.push(n); warn(`could not comment on #${n}: ${String(r.stderr || '').split('\n')[0]}`); }
1575
+ }
1576
+ return { range: `${prev}..${version}`, issues: nums, posted, skipped };
1577
+ }
1578
+
1444
1579
  function cmdReleaseCut(argv) {
1445
1580
  const opts = parseArgs(argv, {
1446
1581
  values: { '--repo': 'repo', '--bump': 'bump', '--reason': 'reason' },
@@ -1485,7 +1620,7 @@ function cmdReleaseCut(argv) {
1485
1620
  const tags = lines(git.git(['tag', '--list'], repoAbs));
1486
1621
  const tagsAtSha = lines(git.git(['tag', '--points-at', sha], repoAbs));
1487
1622
 
1488
- const { ci, suite, schema, switches, issues } = measureCandidateConditions(repoAbs, {
1623
+ const { ci, suite, schema, switches, issues, migrations: migrationPathsSince } = measureCandidateConditions(repoAbs, {
1489
1624
  sha, lastFinal, at, readRuns: () => releaseCut.withoutOwnWorkflow(git.ghRunsForCommit(repoAbs, 'main', sha)), // #425
1490
1625
  });
1491
1626
  const { manifests, ancestry } = measurePreTag(repoAbs, sha, `${remote}/main`); // #424
@@ -1497,9 +1632,17 @@ function cmdReleaseCut(argv) {
1497
1632
  auto = { signals, migration, cadence, promotion: offTrunk ? measurePromotion(repoAbs, { sha, trunk, remote, fetched: trunkFetch }) : null };
1498
1633
  }
1499
1634
 
1635
+ // #446: route deploy-tag-fast — the grant, the human veto, the migration gate and the spacing are
1636
+ // measured only there, so every candidate route's run is what it was.
1637
+ const fast = releaseCut.isFastRoute(policy) && !policy.findings.length;
1638
+ const fastFacts = fast ? measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: migrationPathsSince }) : {};
1639
+ if (fast && auto) auto.spacing = fastFacts.spacing;
1640
+
1500
1641
  const verdict = releaseCut.decide({
1501
1642
  policy, triggers, lastFinal, suggestion, tags, tagsAtSha, ci, suite, schema, switches, manifests, ancestry, auto,
1502
1643
  override: opts.bump ? { bump: opts.bump, reason: opts.reason } : null,
1644
+ finalGrant: fastFacts.finalGrant, holds: fastFacts.holds, migrations: fastFacts.migrations,
1645
+ trackingIssue: fastFacts.tracking ? fastFacts.tracking.number : null,
1503
1646
  });
1504
1647
 
1505
1648
  let created = false;
@@ -1514,19 +1657,53 @@ function cmdReleaseCut(argv) {
1514
1657
  throw new UserError(`git push ${remote} ${verdict.tag} failed — the local tag was deleted again, nothing is cut (${(push.stderr || '').split('\n')[0]})`);
1515
1658
  }
1516
1659
  created = true;
1517
- published = publishPrerelease(repoAbs, { tag: verdict.tag, lastFinal, message });
1660
+ published = publishPrerelease(repoAbs, { tag: verdict.tag, lastFinal, message, final: !!verdict.final });
1518
1661
  }
1519
1662
  // #445: the `next` channel names the newest candidate — fast-forwarded in the run that pushed it.
1520
1663
  // Best-effort like the pre-release: the tag already stands, so a channel that cannot move is reported.
1664
+ // #446: a fast-route final moves `stable` instead — it is the newest final, and there is no candidate.
1521
1665
  const channel = verdict.ok && verdict.tag
1522
- ? releaseChannel.moveChannel(repoAbs, { remote, channel: releaseChannel.CHANNELS.next, sha, label: verdict.tag, dry: !!opts.dry })
1666
+ ? releaseChannel.moveChannel(repoAbs, { remote, channel: verdict.final ? releaseChannel.CHANNELS.stable : releaseChannel.CHANNELS.next, sha, label: verdict.tag, dry: !!opts.dry })
1523
1667
  : null;
1524
1668
 
1669
+ // #446: the fast route's own writes. A final: every issue it carries hears which version has it, and
1670
+ // an open tracking record for the version is closed. An ungranted migration: the hand-off is posted
1671
+ // on the version's tracking issue (opened if there is none), for a human to grant.
1672
+ let announced = null;
1673
+ let handoff = verdict.handoff || null;
1674
+ if (fast && !opts.dry) {
1675
+ if (created) {
1676
+ const exclude = (issues || []).filter((i) => releaseFinalize.parseReleaseMarker(i.body)).map((i) => i.number);
1677
+ announced = announceCarried(repoAbs, { tagNames: [...tags, verdict.tag], exclude, version: verdict.tag, sha });
1678
+ if (fastFacts.tracking) {
1679
+ 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.`);
1680
+ const r = tracker.forRepo(repoAbs).issueClose(fastFacts.tracking.number);
1681
+ if (!r.ok) warn(`could not close #${fastFacts.tracking.number}: ${String(r.stderr || '').split('\n')[0]}`);
1682
+ }
1683
+ } else if (handoff && verdict.version) {
1684
+ let num = fastFacts.tracking ? fastFacts.tracking.number : null;
1685
+ if (!num && issues !== null) {
1686
+ const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(verdict.version), body: releaseCut.handoffTrackingBody(verdict.version) });
1687
+ if (c.number) num = c.number;
1688
+ 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`);
1689
+ }
1690
+ if (num) {
1691
+ handoff = releaseCut.migrationHandoff(num, verdict.version);
1692
+ commentOnce(repoAbs, num, { state: 'migration-handoff', version: verdict.version },
1693
+ `**${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\`\`\``);
1694
+ }
1695
+ }
1696
+ }
1697
+
1525
1698
  if (opts.json) {
1526
1699
  print(JSON.stringify({
1527
1700
  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,
1701
+ ok: verdict.ok, noop: !!verdict.noop, standing: verdict.standing || [], tag: verdict.tag, created, published, channel, version: verdict.version, bump: verdict.bump,
1529
1702
  overridden: verdict.overridden, signals: verdict.signals ? verdict.signals.lines : null, checks: verdict.checks,
1703
+ // #446: present on every route, so the workflow reads one shape — final only on deploy-tag-fast.
1704
+ final: !!verdict.final,
1705
+ deploy: verdict.final && verdict.healthGate ? { healthUrl: verdict.healthGate.url, rollback: verdict.healthGate.rollback } : null,
1706
+ grant: verdict.grant || null, handoff, ...(fast ? { announced } : {}),
1530
1707
  }, null, 2));
1531
1708
  return verdict.ok || verdict.noop ? 0 : 1;
1532
1709
  }
@@ -1540,14 +1717,27 @@ function cmdReleaseCut(argv) {
1540
1717
  for (const c of verdict.checks) print(` ${c.ok ? '✓' : '✗'} ${c.condition.padEnd(width)} ${c.detail}`);
1541
1718
  print('');
1542
1719
  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.');
1720
+ print(fast
1721
+ ? '· no-op — nothing owed, inside release.final-spacing, or main\'s head already carries a final; nothing tagged.'
1722
+ : '· no-op — nothing owed, inside the route\'s cadence window, or main\'s head is not a promotion of trunk; nothing cut.');
1544
1723
  return 0;
1545
1724
  }
1546
1725
  if (!verdict.ok) {
1547
1726
  print(`✗ refused — ${verdict.refusals.length} condition(s) failed; nothing cut.`);
1727
+ // #467: a refusal no further run clears by itself is a stall — say so, so nobody waits on it.
1728
+ 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).`);
1729
+ if (handoff) print(`\nA migration rides this release. The one command, for a human to run:\n ${handoff}`);
1548
1730
  return 1;
1549
1731
  }
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.`);
1732
+ if (verdict.final) {
1733
+ 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.`);
1734
+ else {
1735
+ 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.`);
1736
+ if (published && published.ok) print(`✓ ${published.detail}`);
1737
+ else if (published) warn(`${published.detail} — the tag stands; publish it by hand: gh release create ${verdict.tag} --verify-tag --latest`);
1738
+ if (announced && announced.issues.length) print(`released in ${verdict.tag}: told ${announced.posted.length ? announced.posted.map((n) => `#${n}`).join(', ') : 'nobody new'}`);
1739
+ }
1740
+ } 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
1741
  else {
1552
1742
  print(`✓ cut ${verdict.tag} on ${at} and pushed it to ${remote} — a candidate, not a release; finalizing it is the release skill's.`);
1553
1743
  if (published && published.ok) print(`✓ ${published.detail}`);
@@ -1566,23 +1756,25 @@ function cmdReleaseCut(argv) {
1566
1756
  * workflow raced us) is left alone. Best-effort: the tag is already on origin, so a failure here is
1567
1757
  * reported, never a reason to undo the cut.
1568
1758
  */
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` };
1759
+ function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false }) {
1760
+ // #446: a deploy-tag-fast final is published as a full release, marked latest.
1761
+ const kind = final ? 'release' : 'pre-release';
1762
+ if (!isGhUsable(repoAbs)) return { ok: false, detail: `${kind} NOT published: gh not usable (${ghUnusableWhy(repoAbs)})` };
1763
+ const view = tracker.forRepo(repoAbs).releaseView(tag);
1764
+ if (view.ok) return { ok: true, detail: `${tag} already has a GitHub Release — left as it is` };
1573
1765
  let notes;
1574
1766
  try {
1575
1767
  notes = lastFinal ? buildReleaseNotes(repoAbs, `${lastFinal}..${tag}`, lastFinal).out : `## ${tag}\n\nFirst release.\n`;
1576
1768
  } catch (e) {
1577
1769
  notes = `## ${tag}\n\n(release notes unavailable: ${e.message})\n`;
1578
1770
  }
1579
- notes += `\n### Candidate record\n\n\`\`\`\n${message}\`\`\`\n`;
1771
+ notes += `\n### ${final ? 'Release' : 'Candidate'} record\n\n\`\`\`\n${message}\`\`\`\n`;
1580
1772
  const file = path.join(os.tmpdir(), `colab-release-notes-${process.pid}-${tag}.md`);
1581
1773
  fs.writeFileSync(file, notes);
1582
1774
  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}` };
1775
+ const r = tracker.forRepo(repoAbs).releaseCreate(tag, { notesFile: file, final });
1776
+ if (!r.ok) return { ok: false, detail: `${kind} NOT published: gh release create ${tag} failed (${(r.stderr || '').split('\n')[0] || r.code})` };
1777
+ return { ok: true, detail: `published the GitHub ${kind} ${tag}` };
1586
1778
  } finally {
1587
1779
  try { fs.unlinkSync(file); } catch (_) { /* best-effort */ }
1588
1780
  }
@@ -1659,8 +1851,8 @@ Conditions (--json checks[].condition; required:false means reported, not blocki
1659
1851
 
1660
1852
  manifest-version on-trunk outranks-final — #424's pre-tag checks, required before any final:
1661
1853
  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
1854
+ checkout refuses), and it outranks the highest final tag. Under release.version-source:
1855
+ tag (#438; the default where the machine cuts the tag, #484) a manifest that differs is skipped as derivable and named, not refused
1664
1856
 
1665
1857
  final-grant migration-grant — #441, only where release.final-grant lets a deploy-tag final be
1666
1858
  automatic: the decision issue it names must still carry a recorded, trusted, not
@@ -1774,10 +1966,9 @@ function cmdReleaseFinalize(argv) {
1774
1966
  const t0 = version0 ? trackings.get(version0) : null;
1775
1967
  if (newest && t0 && !t0.error && !t0.number && !opts.dry) {
1776
1968
  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; }
1969
+ const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(version0), body });
1970
+ 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'})` });
1971
+ else { trackings.set(version0, { number: c.number, url: c.url, createdAt: now, held: false }); trackingCreated = true; }
1781
1972
  }
1782
1973
 
1783
1974
  // #441: an operator-granted automatic final — the decision it names is resolved once per run, from
@@ -1829,7 +2020,7 @@ function cmdReleaseFinalize(argv) {
1829
2020
  manifests, ancestry, tags: tagNames, finalGrant, migrations,
1830
2021
  human: { bar: humanBar, answeredBy: opts.answeredBy || null },
1831
2022
  });
1832
- return { candidate: cand, verdict, period, tracking };
2023
+ return { candidate: cand, verdict, period, tracking, trunk };
1833
2024
  };
1834
2025
 
1835
2026
  let cand = null; let verdict; let period = null; let tracking = version0 ? trackings.get(version0) : null;
@@ -1837,14 +2028,23 @@ function cmdReleaseFinalize(argv) {
1837
2028
  if (walk) {
1838
2029
  const MAX_JUDGED = 10;
1839
2030
  const evals = [];
2031
+ // #468: every red trunk run a judged candidate's window held. One red run puts every candidate cut
2032
+ // in the test period before it into needs-new-candidate; on a repo cutting several a day, judging
2033
+ // each one in full spent MAX_JUDGED on them and the walk stopped before the older clean one.
2034
+ const knownRed = [];
1840
2035
  for (const c of releaseFinalize.openCandidates(tags, remote)) {
1841
- if (c.refused) { skipped.push({ tag: c.tag, state: 'refused', detail: c.refused }); continue; }
2036
+ if (c.refused) { skipped.push({ tag: c.tag, state: 'refused', detail: c.refused, endsAt: null }); continue; }
1842
2037
  const tr = trackings.has(c.version) ? trackings.get(c.version) : trackingFor(c.version, { isCandidate: true });
1843
2038
  const p = releaseFinalize.periodVerdict({ cutAt: c.cutAt, trackingCreatedAt: tr && tr.createdAt, testPeriodDays: policy.effective.testPeriodDays, now });
1844
2039
  // 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; }
2040
+ if (!p.elapsed && evals.length) { skipped.push({ tag: c.tag, state: 'testing', detail: `test-period: ${p.detail}`, endsAt: p.endsAt }); continue; }
2041
+ // #468: cheap skip, the second kind — a red run already seen inside this candidate's own window.
2042
+ // Not counted toward MAX_JUDGED. May be wrong only in the safe direction (windowHasRed).
2043
+ const seenRed = evals.length ? releaseFinalize.windowHasRed(p, knownRed) : null;
2044
+ 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
2045
  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
2046
  evals.push(e);
2047
+ if (e.trunk && Array.isArray(e.trunk.redAt)) knownRed.push(...e.trunk.redAt);
1848
2048
  if (e.verdict.state === 'finalized' || e.verdict.state === 'held' || evals.length >= MAX_JUDGED) break;
1849
2049
  }
1850
2050
  const pick = releaseFinalize.pickNewestClean(evals);
@@ -1871,28 +2071,13 @@ function cmdReleaseFinalize(argv) {
1871
2071
  if (!r.ok) warn(`could not comment on #${num}: ${String(r.stderr || '').split('\n')[0]}`);
1872
2072
  };
1873
2073
  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]}`);
2074
+ const r = tracker.forRepo(repoAbs).issueClose(num);
2075
+ if (!r.ok) warn(`could not close #${num}: ${String(r.stderr || '').split('\n')[0]}`);
1876
2076
  };
1877
2077
  // #426: one "Released in vX.Y.Z" comment on every issue the version carries (release-finalize.js
1878
2078
  // carriedIssues — the closing references in (previous final, sha]). Idempotent by event marker.
1879
2079
  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
- };
2080
+ const announceRelease = (version, sha) => announceCarried(repoAbs, { tagNames, exclude: records.map((r) => r.number), version, sha });
1896
2081
  if (!opts.dry) {
1897
2082
  if (verdict.state === 'finalized') {
1898
2083
  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 +2141,16 @@ function cmdReleaseFinalize(argv) {
1956
2141
  const trackingOut = tracking && !tracking.error
1957
2142
  ? { number: tracking.number || null, url: tracking.url || null, created: trackingCreated && (!cand || cand.version === version0), held: !!tracking.held, supersededHeld }
1958
2143
  : null;
2144
+ // #468: why this run made no final, and which candidate finals first — the line the release
2145
+ // workflow prints, so "no final" never has to be reconstructed from a checklist.
2146
+ const why = releaseFinalize.whyNoFinal({ state: verdict.state, candidate: cand, checks: verdict.checks, period, skipped: walk ? skipped : [], now });
1959
2147
  if (opts.json) {
1960
2148
  print(JSON.stringify({
1961
2149
  repo: shortRepo(repoAbs), row: policy.derived.row, route: policy.effective.route, final: policy.effective.final, testPeriodDays: policy.effective.testPeriodDays,
1962
2150
  lastFinal, dry: !!opts.dry, auto: !!opts.auto, candidate: cand, tracking: trackingOut,
1963
2151
  periodStart: period ? period.start : null, periodEndsAt: period ? period.endsAt : null,
1964
2152
  state: verdict.state, tagged, finalTag: verdict.finalTag, checks: verdict.checks, handoff: verdict.handoff,
1965
- skipped: walk ? skipped : undefined, announced, grant: verdict.grant || null, channel,
2153
+ skipped: walk ? skipped : undefined, why, next: why ? why.next : null, announced, grant: verdict.grant || null, channel,
1966
2154
  }, null, 2));
1967
2155
  } else {
1968
2156
  print(`colab release finalize${opts.auto ? ' --auto' : ''} — ${shortRepo(repoAbs)} (last final: ${lastFinal || 'none'}${cand ? `, candidate: ${cand.tag}` : ''})`);
@@ -1974,6 +2162,7 @@ function cmdReleaseFinalize(argv) {
1974
2162
  }
1975
2163
  print('');
1976
2164
  print(`state: ${verdict.state}${opts.dry ? ' [--dry: nothing written]' : ''}${tagged ? ` — tagged ${verdict.finalTag} and pushed it to ${remote}` : ''}`);
2165
+ if (why) print(`why no final: ${why.line}`);
1977
2166
  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
2167
  if (channel && channel.ok) print(`✓ ${channel.detail}`);
1979
2168
  else if (channel) warn(`${channel.detail} — the final tag stands`);
@@ -2039,7 +2228,7 @@ function cmdRelease(argv) {
2039
2228
  });
2040
2229
  if (opts.help || opts._.length === 0) return print(HELP_RELEASE);
2041
2230
  const num = normIssueNum(opts._[0]);
2042
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
2231
+ const repoAbs = resolveRepoOrCwd(opts);
2043
2232
 
2044
2233
  // #164: look the claim up WITHOUT deleting it yet — the gh write below can fail (GraphQL AND
2045
2234
  // REST both rate-limited, network down, ...), and deleting first would clear the one local
@@ -2065,7 +2254,7 @@ function cmdRelease(argv) {
2065
2254
  * Returns { ghFailed, worktree, remaining }.
2066
2255
  */
2067
2256
  function releaseFoundClaim(num, found, opts = {}) {
2068
- const repo = found.claim.repo;
2257
+ const repo = found.repo || found.claim.repo; // #487: the MAIN root, even for a legacy worktree-keyed row
2069
2258
  const wtName = found.claim.worktree;
2070
2259
 
2071
2260
  let ghFailed = false;
@@ -2188,7 +2377,7 @@ function cmdIssueFiled(argv) {
2188
2377
  });
2189
2378
  if (opts.help || opts._.length === 0) return print(HELP_ISSUE_FILED);
2190
2379
  const num = normIssueNum(opts._[0]);
2191
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
2380
+ const repoAbs = resolveRepoOrCwd(opts);
2192
2381
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
2193
2382
 
2194
2383
  pushEvent('issue-filed', { repo: repoAbs, issue: num });
@@ -2283,7 +2472,7 @@ function cmdClose(argv) {
2283
2472
  if (already) {
2284
2473
  print(` #${num} is already closed — skipping the close; releasing and notifying anyway`);
2285
2474
  } else {
2286
- const r = git.run('gh', ['issue', 'close', String(num), '--reason', ghReason], { cwd: repoAbs });
2475
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: ghReason });
2287
2476
  if (!r.ok) {
2288
2477
  process.stderr.write(`✗ gh issue close #${num} failed (${(r.stderr || '').split('\n')[0] || r.code}) — claim untouched.\n`);
2289
2478
  return 1;
@@ -2360,7 +2549,7 @@ function cmdGateRecorded(argv) {
2360
2549
  });
2361
2550
  if (opts.help) return print(HELP_GATE_RECORDED);
2362
2551
 
2363
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.mainRepoRoot(process.cwd()) || null);
2552
+ const repoAbs = resolveRepoOrCwd(opts);
2364
2553
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
2365
2554
 
2366
2555
  let wtName = opts.worktree || null;
@@ -3134,7 +3323,7 @@ function cmdReadiness(argv) {
3134
3323
  });
3135
3324
  if (opts.help || opts._.length === 0) return print(HELP_READINESS);
3136
3325
  const num = normIssueNum(opts._[0]);
3137
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
3326
+ const repoAbs = resolveRepoOrCwd(opts);
3138
3327
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3139
3328
 
3140
3329
  // No local fallback, on purpose. A claim can degrade to local-only because it also has a fast
@@ -3334,7 +3523,7 @@ function cmdBlocked(argv) {
3334
3523
  });
3335
3524
  if (argErr) throw new UserError(argErr);
3336
3525
 
3337
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
3526
+ const repoAbs = resolveRepoOrCwd(opts);
3338
3527
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3339
3528
 
3340
3529
  if (!isGhUsable(repoAbs)) {
@@ -3531,17 +3720,28 @@ ROLE-TAGGED GRANTS (#397). --role defaults to \`human\` — the grant above, unc
3531
3720
  --role ${migrationGrant.REVIEWER_ROLE} the comment is a \`${migrationGrant.REVIEW_GRANT_MARK}\` instead:
3532
3721
  it names the declared reviewer and carries a REVIEW RECORD (a \`\`\`${migrationGrant.REVIEW_RECORD_FENCE}
3533
3722
  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.
3723
+ the reviewed HEAD sha, and — #508 — \`migrations\`, a content id over the branch's migration files at
3724
+ that HEAD, computed here, never a flag). A reviewer grant is bound to that CONTENT: a commit that
3725
+ leaves every migration file byte-identical (the trunk sync ship requires) keeps it; editing, adding,
3726
+ removing or renaming a migration voids it. A branch with no migration file gets no id and is bound to
3727
+ its HEAD alone, as is every record minted before #508.
3535
3728
  It is minted only when ALL of these hold, checked before any network call:
3536
3729
  - the record is well-formed AND passing (approve · checklist pass · escalation clear · CI pass) —
3537
3730
  a grant carrying a failing review is a contradiction, so it is refused, not recorded;
3538
3731
  - 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).
3732
+ - this checkout's project.yml declares \`migration-grant: reviewer\` (#398; absent = human);
3733
+ - checklist-items, when given, is <passed>/${migrationGrant.REVIEW_CHECKLIST_ITEMS} and, with checklist pass, every item
3734
+ passed (#457) — the record counts against the checklist the migration-review skill walks today.
3735
+ Then, read from CI after the tracker read and before anything is written (#457):
3736
+ - ci-roundtrip pass is TRUE at the head: the "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" job ran and
3737
+ passed there (the rule ship applies), and --ci-run, when given, is one of the runs at that
3738
+ head and carries the job. A repo whose CI has no such job cannot mint a reviewer grant at all.
3540
3739
  COLAB_HUMAN=1 is still required for every role. The reviewer identity is DECLARED, not attested.
3541
3740
  \`colab ship\` honours a reviewer grant only when ALL of (#401): P the target's project.yml says
3542
3741
  \`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.
3742
+ branch's exact remote head, or its \`migrations\` id equals the id at that head · R the live
3743
+ "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job passed on the SHIPPED head (re-read by ship, never
3744
+ taken from the record). Any condition failing → a human runs Phase B.
3545
3745
 
3546
3746
  Options:
3547
3747
  --branch <branch> required for --branch grants; a grant is never inferred from HEAD
@@ -3589,7 +3789,7 @@ function cmdMigrationGrant(argv) {
3589
3789
  return 1;
3590
3790
  }
3591
3791
 
3592
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
3792
+ const repoAbs = resolveRepoOrCwd(opts);
3593
3793
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3594
3794
 
3595
3795
  // Argument validation and local ref resolution run BEFORE isGhUsable, deliberately — they are
@@ -3660,11 +3860,22 @@ function migrationGrantReviewRecord(repoAbs, opts) {
3660
3860
  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
3861
  }
3662
3862
 
3863
+ // #508: bind what was reviewed — the branch's migration files at the tip, by content. Same path
3864
+ // rule the ship gate fires on (newMigrations), against origin's trunk. A branch with no migration
3865
+ // to review gets no id and stays HEAD-bound.
3866
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
3867
+ const remote = git.remoteInfo(repoAbs).name || 'origin';
3868
+ let base = trunk ? `${remote}/${trunk}` : null;
3869
+ if (base && !git.git(['rev-parse', '--verify', '--quiet', `${base}^{commit}`], repoAbs).ok) base = trunk;
3870
+ const migrations = base ? newMigrations(repoAbs, base, tip) : [];
3871
+ const contentId = migrationContentAt(repoAbs, migrations, tip);
3872
+
3663
3873
  const rec = {
3664
3874
  v: '1', role, reviewer: opts.reviewer, head: tip,
3665
3875
  verdict: opts.verdict, checklist: opts.checklist, 'checklist-items': opts.checklistItems,
3666
3876
  escalation: opts.escalation, 'escalation-result': opts.escalationResult,
3667
3877
  'ci-roundtrip': opts.ciRoundtrip, 'ci-run': opts.ciRun,
3878
+ migrations: contentId || undefined,
3668
3879
  };
3669
3880
  for (const k of Object.keys(rec)) if (rec[k] === undefined) delete rec[k];
3670
3881
  const v = migrationGrant.validateReviewRecord(rec);
@@ -3672,9 +3883,36 @@ function migrationGrantReviewRecord(repoAbs, opts) {
3672
3883
  if (!v.passing) {
3673
3884
  throw new UserError(`the review does not pass (${migrationGrant.reviewRecordFailure(rec)}) — a grant carrying a failing review is a contradiction; nothing was posted`);
3674
3885
  }
3886
+ // #457: checks only a NEW record faces (the checklist denominator) — local, so before the gh gate.
3887
+ const mintProblems = migrationGrant.mintRecordProblems(rec);
3888
+ if (mintProblems.length) throw new UserError(`the review record is invalid: ${mintProblems.join('; ')}`);
3675
3889
  return rec;
3676
3890
  }
3677
3891
 
3892
+ /**
3893
+ * #457: the record says `ci-roundtrip: pass` — read CI at its head and refuse unless the round-trip
3894
+ * job is really there and passed (tools/lib/migration-grant.js mintRoundtripCheck: the same
3895
+ * roundtripVerdict `colab ship` applies, plus the cited `ci-run` must carry the job). Needs gh, so
3896
+ * it runs in cmdMigrationGrantCreate after the tracker read and BEFORE the label is applied —
3897
+ * nothing is written when it refuses. The workflows guard diffs trunk against the reviewed head;
3898
+ * an unreadable diff counts as touched, failing closed exactly as shipMigrationCtx does.
3899
+ */
3900
+ function migrationGrantRoundtripCheck(repoAbs, branch, rec) {
3901
+ if (rec['ci-roundtrip'] !== 'pass') return;
3902
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
3903
+ const remote = git.remoteInfo(repoAbs).name || 'origin';
3904
+ let d = trunk ? git.git(['diff', '--name-only', `${remote}/${trunk}...${rec.head}`], repoAbs) : { ok: false };
3905
+ if (!d.ok && trunk) d = git.git(['diff', '--name-only', `${trunk}...${rec.head}`], repoAbs);
3906
+ const workflowsTouched = !d.ok || d.stdout.split('\n').some((f) => f.startsWith('.github/workflows/'));
3907
+ let runs = null;
3908
+ const list = git.ghRunsForCommit(repoAbs, branch, rec.head, 20);
3909
+ if (Array.isArray(list)) {
3910
+ runs = list.map((r) => ({ databaseId: r.databaseId, workflowName: r.workflowName || null, jobs: git.ghRunJobs(repoAbs, r.databaseId) }));
3911
+ }
3912
+ const c = migrationGrant.mintRoundtripCheck(rec, runs, { workflowsTouched });
3913
+ if (!c.ok) throw new UserError(`${c.reason}; nothing was posted`);
3914
+ }
3915
+
3678
3916
  function cmdMigrationGrantCreate(repoAbs, num, opts) {
3679
3917
  // --branch and branch existence are already validated by cmdMigrationGrant, ahead of the
3680
3918
  // isGhUsable gate — see the comment there. Kept as a defensive re-check in case this function is
@@ -3698,6 +3936,9 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
3698
3936
  || `this repo has no \`${labels.MIGRATION_GRANT_LABEL}\` label`);
3699
3937
  }
3700
3938
 
3939
+ // #457: a record claiming a CI round-trip pass is checked against CI BEFORE anything is written.
3940
+ if (opts.reviewRecord) migrationGrantRoundtripCheck(repoAbs, opts.branch, opts.reviewRecord);
3941
+
3701
3942
  const editR = git.ghIssueEdit(repoAbs, num, labels.migrationGrantLabelArgs({}));
3702
3943
  if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
3703
3944
 
@@ -3717,7 +3958,11 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
3717
3958
 
3718
3959
  if (opts.reviewRecord) {
3719
3960
  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.');
3961
+ if (opts.reviewRecord.migrations) {
3962
+ 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.`);
3963
+ } else {
3964
+ print(' Bound to that HEAD: any new commit voids it. It expires the moment the issue closes.');
3965
+ }
3721
3966
  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
3967
  print(` Revoke any time: colab migration-grant ${num} --revoke`);
3723
3968
  return 0;
@@ -3765,7 +4010,7 @@ function cmdMigrationGrantRevoke(repoAbs, num) {
3765
4010
  }
3766
4011
 
3767
4012
  function cmdMigrationGrantList(opts) {
3768
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4013
+ const repoAbs = resolveRepoOrCwd(opts);
3769
4014
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3770
4015
  if (!isGhUsable(repoAbs)) {
3771
4016
  throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — cannot list migration grants`);
@@ -3900,7 +4145,7 @@ function cmdDecision(argv) {
3900
4145
  throw new UserError('--ruled-by <name> is required — names the human whose call this is, never the typist (CONVENTIONS.md §5, Provenance)');
3901
4146
  }
3902
4147
 
3903
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4148
+ const repoAbs = resolveRepoOrCwd(opts);
3904
4149
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
3905
4150
 
3906
4151
  if (!isGhUsable(repoAbs)) {
@@ -4046,7 +4291,7 @@ function cmdDecisionReopen(repoAbs, num, opts, body) {
4046
4291
  }
4047
4292
 
4048
4293
  function cmdDecisionList(opts) {
4049
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4294
+ const repoAbs = resolveRepoOrCwd(opts);
4050
4295
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4051
4296
  if (!isGhUsable(repoAbs)) {
4052
4297
  throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — cannot list decisions`);
@@ -4128,6 +4373,7 @@ function cmdDecisionList(opts) {
4128
4373
  // ---------------------------------------------------------------------------
4129
4374
 
4130
4375
  const HELP_CI_GRANT = `colab ci-grant <issue> --branch <branch> [--evidence-run <sha-or-url>] [--repo <path>]
4376
+ colab ci-grant <issue> --branch <branch> --role ci-reviewer --reviewer <id> --verdict pass --cures <checks> [--repo <path>]
4131
4377
  colab ci-grant <issue> --revoke [--repo <path>]
4132
4378
  colab ci-grant --list [--json] [--repo <path>]
4133
4379
 
@@ -4166,8 +4412,9 @@ CI grant merges into a repo whose own test suite is known-failing:
4166
4412
  \`ship\` would never consult it for, reading live in \`--list\` while doing nothing.
4167
4413
 
4168
4414
  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.
4415
+ environment — the identical bar \`colab promote\`/\`colab migration-grant\` already hold. This check
4416
+ runs BEFORE any network call. The ONE exception is the reviewer role below, and only on a repo whose
4417
+ trunk opts in.
4171
4418
 
4172
4419
  The marker is TWO parts, both required for a grant to read as live:
4173
4420
  - the \`${labels.CI_GRANT_LABEL}\` label — applying it requires GitHub write/triage permission, so
@@ -4195,8 +4442,30 @@ Revoking removes the label FIRST (the gate is restored the same minute) and post
4195
4442
  There is deliberately no local-only fallback: without a usable \`gh\`, every subcommand here REFUSES
4196
4443
  rather than write (or read) something invisible to the machine \`ship\` might later run on.
4197
4444
 
4445
+ THE REVIEWER ROLE (#504). On a repo whose TRUNK declares \`ci-grant: reviewer\` in project.yml,
4446
+ --role ${ciGrant.REVIEWER_ROLE} mints a \`${ciGrant.REVIEW_GRANT_MARK}\` WITHOUT COLAB_HUMAN=1 — the coordinator
4447
+ agent's door through a red trunk the cure rule refuses (maintainer ruling 2026-10-05). It is the only
4448
+ path past the human bar above, and only that opt-in opens it; revoking stays human. Every guard is
4449
+ measured, nothing is taken from the flags:
4450
+ - local, before any network call: the opt-in on trunk as committed (a branch cannot opt itself
4451
+ in) · the record is well-formed with --verdict pass and at least one cure · the branch is
4452
+ pushed and --head (if given) is origin's tip · the branch's trailing number group carries #N;
4453
+ - #N is open and its title starts "${ciGrant.TRUNK_RED_TITLE_PREFIX}" · trunk is red in ship's sense ·
4454
+ never stacks (guard 2 above) · the branch's own CI is green at that EXACT head · every
4455
+ check in --cures is red on trunk at the red sha.
4456
+ The comment carries a fenced \`ci-review\` record (verdict, head, red sha, cures) and binds that
4457
+ HEAD and that red sha: a new commit on either voids it. \`colab ship\` re-measures all of it, reads
4458
+ the opt-in at the merge target, and reads a grant with \`not-before\` in the future as not yet usable.
4459
+
4198
4460
  Options:
4199
4461
  --branch <branch> required for a grant; never inferred from HEAD
4462
+ --role <role> human (default) | ${ciGrant.REVIEWER_ROLE}
4463
+ --reviewer <id> (reviewer) the reviewer's declared identity (letters, digits, . _ @ -)
4464
+ --verdict <v> (reviewer) pass | fail — only pass is minted
4465
+ --cures <checks> (reviewer) the red checks the branch cures, "workflow / job; …"
4466
+ --head <sha> (reviewer) optional; must equal the pushed branch tip
4467
+ --not-before <iso> (reviewer) optional; a revoke window the host imposes
4468
+ --ci-run <id-or-url> (reviewer) optional; recorded only
4200
4469
  --evidence-run <ref> recording-only note for the audit trail — never substitutes for the
4201
4470
  measured branch-head run this command itself checks
4202
4471
  --revoke revoke instead of grant
@@ -4225,7 +4494,10 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4225
4494
  let priorGrantMerge = null;
4226
4495
  if (priorLog.ok && priorLog.stdout.trim()) {
4227
4496
  const [sha, at] = priorLog.stdout.trim().split('\n')[0].split('\t');
4228
- priorGrantMerge = { sha, at };
4497
+ // #477: the red sha that exemption was measured against, off its own trailer — what the cure
4498
+ // rule's progress admission compares today's red set with. null when unreadable (refuses there).
4499
+ const body = git.git(['log', '-1', '--format=%B', sha], repoAbs);
4500
+ priorGrantMerge = { sha, at, redSha: body.ok ? ciCure.priorRedShaFromMessage(body.stdout) : null };
4229
4501
  }
4230
4502
  let redContinuousSincePriorGrant = false;
4231
4503
  if (priorGrantMerge) {
@@ -4237,11 +4509,10 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4237
4509
  // local offset is positive (tools/lib/ci-grant.js's wentGreenSince doc comment has the full
4238
4510
  // failure).
4239
4511
  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) {
4512
+ const runsR = tracker.forRepo(repoAbs).runList({ branch: trunk, limit: 100, fields: ['conclusion', 'status', 'createdAt'] });
4513
+ if (runsR.data) {
4243
4514
  try {
4244
- wentGreen = ciGrant.wentGreenSince(JSON.parse(runsR.stdout), priorGrantMerge.at);
4515
+ wentGreen = ciGrant.wentGreenSince(runsR.data, priorGrantMerge.at);
4245
4516
  } catch (_) { /* unparseable — treat conservatively as "cannot prove it went green" */ }
4246
4517
  }
4247
4518
  redContinuousSincePriorGrant = !wentGreen;
@@ -4251,7 +4522,12 @@ function computeAntiStacking(repoAbs, trunk, trunkIsRed) {
4251
4522
 
4252
4523
  function cmdCiGrant(argv) {
4253
4524
  const opts = parseArgs(argv, {
4254
- values: { '--repo': 'repo', '--branch': 'branch', '--evidence-run': 'evidenceRun' },
4525
+ values: {
4526
+ '--repo': 'repo', '--branch': 'branch', '--evidence-run': 'evidenceRun',
4527
+ // #504 reviewer-grant record flags
4528
+ '--role': 'role', '--reviewer': 'reviewer', '--verdict': 'verdict', '--cures': 'cures',
4529
+ '--head': 'head', '--not-before': 'notBefore', '--ci-run': 'ciRun',
4530
+ },
4255
4531
  flags: { '--revoke': 'revoke', '--list': 'list', '--json': 'json', '-h': 'help', '--help': 'help' },
4256
4532
  });
4257
4533
  if (opts.help) return print(HELP_CI_GRANT);
@@ -4259,15 +4535,31 @@ function cmdCiGrant(argv) {
4259
4535
  if (opts._.length === 0) return print(HELP_CI_GRANT);
4260
4536
  const num = normIssueNum(opts._[0]);
4261
4537
 
4538
+ // #504: the reviewer role is the ONE path past the human bar below, and only on a repo whose
4539
+ // TRUNK declares `ci-grant: reviewer`. Decided from local git alone, before any network call.
4540
+ const role = opts.role === undefined ? 'human' : String(opts.role);
4541
+ if (!ciGrant.GRANT_ROLES.includes(role)) {
4542
+ throw new UserError(`--role is "${role}", expected ${ciGrant.GRANT_ROLES.join(' | ')}`);
4543
+ }
4544
+ if (opts.revoke && opts.role !== undefined) {
4545
+ throw new UserError('--revoke takes no --role — a revoke cancels every live grant on the issue, whatever its role');
4546
+ }
4547
+ if (role === ciGrant.REVIEWER_ROLE && !opts.revoke) return cmdCiGrantReviewer(num, opts);
4548
+ const stray = ['reviewer', 'verdict', 'cures', 'head', 'notBefore', 'ciRun'].filter((k) => opts[k] !== undefined);
4549
+ if (stray.length) {
4550
+ 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`);
4551
+ }
4552
+
4262
4553
  // HUMAN-ONLY, first — identical posture and identical reason to cmdMigrationGrant's check above:
4263
4554
  // assertable by a test against a fixture with no `gh` at all (tools/lib/ship-ci-grant.test.js).
4264
4555
  if (process.env.COLAB_HUMAN !== '1') {
4265
4556
  process.stderr.write(`✗ Refusing: ${opts.revoke ? 'revoking' : 'creating'} a CI grant requires a human.\n`);
4266
4557
  process.stderr.write(' Re-run with COLAB_HUMAN=1. (No field, flag or project.yml value can lower this bar.)\n');
4558
+ 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
4559
  return 1;
4268
4560
  }
4269
4561
 
4270
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4562
+ const repoAbs = resolveRepoOrCwd(opts);
4271
4563
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4272
4564
 
4273
4565
  // Argument validation and local ref resolution BEFORE isGhUsable — same reasoning as
@@ -4287,6 +4579,121 @@ function cmdCiGrant(argv) {
4287
4579
  return opts.revoke ? cmdCiGrantRevoke(repoAbs, num) : cmdCiGrantCreate(repoAbs, num, opts);
4288
4580
  }
4289
4581
 
4582
+ /**
4583
+ * #504: `colab ci-grant <N> --role ci-reviewer` — the coordinator agent's door through a red trunk the
4584
+ * cure rule refuses. Needs no COLAB_HUMAN=1, and that is the whole point; what replaces the human is
4585
+ * the opt-in on trunk plus guards that are all MEASURED here, never taken from the flags:
4586
+ * local (before any network call): `ci-grant: reviewer` committed on trunk · the record is
4587
+ * well-formed with verdict pass and at least one cure · the branch is pushed and --head (if
4588
+ * given) is its remote tip · the branch name's trailing number group carries #N;
4589
+ * tracker/CI: #N is open and titled `TRUNK RED:` · trunk is red in the sense ship checks · never
4590
+ * stacks (computeAntiStacking, same as the human grant) · the branch's own CI is green at that
4591
+ * EXACT head · every claimed cure is a red check on trunk at the red sha.
4592
+ * Nothing is written until all of them pass.
4593
+ */
4594
+ function cmdCiGrantReviewer(num, opts) {
4595
+ const repoAbs = resolveRepoOrCwd(opts);
4596
+ if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4597
+ if (!opts.branch) {
4598
+ throw new UserError('--branch <branch> is required — a grant is bound to one branch, never inferred from the current checkout');
4599
+ }
4600
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
4601
+ if (!trunk) throw new UserError('Could not determine trunk branch (set project.yml trunk:)');
4602
+
4603
+ // The opt-in, read from TRUNK as committed — never this checkout or the branch, so a branch cannot
4604
+ // grant itself the policy it would then use.
4605
+ const pol = ciGrant.parseGrantPolicy(projectDocAt(repoAbs, trunk));
4606
+ if (!pol.valid) throw new UserError(`${pol.reason} — fix project.yml on ${trunk} before minting a reviewer grant`);
4607
+ if (pol.policy !== 'reviewer') {
4608
+ 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`);
4609
+ process.stderr.write(' Without that opt-in a CI grant is human-only: COLAB_HUMAN=1 colab ci-grant <N> --branch <b>.\n');
4610
+ return 1;
4611
+ }
4612
+
4613
+ if (!branchName.branchIssueNumbers(opts.branch).includes(num)) {
4614
+ 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`);
4615
+ }
4616
+ const refs = git.branchRefs(repoAbs, opts.branch);
4617
+ if (!refs.remoteSha) {
4618
+ throw new UserError(`branch "${opts.branch}" is not on origin — a reviewer grant binds the pushed HEAD, so push it first`);
4619
+ }
4620
+ const head = refs.remoteSha.toLowerCase();
4621
+ if (opts.head !== undefined && String(opts.head).toLowerCase() !== head) {
4622
+ 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`);
4623
+ }
4624
+ const rec = {
4625
+ v: '1', role: ciGrant.REVIEWER_ROLE, reviewer: opts.reviewer, head, red: '0'.repeat(40),
4626
+ verdict: opts.verdict, cures: opts.cures === undefined ? undefined : ciGrant.formatCures(ciGrant.parseCures(opts.cures)),
4627
+ 'not-before': opts.notBefore, 'ci-run': opts.ciRun,
4628
+ };
4629
+ for (const k of Object.keys(rec)) if (rec[k] === undefined || rec[k] === '') delete rec[k];
4630
+ const v0 = ciGrant.validateReviewRecord(rec);
4631
+ if (!v0.valid) throw new UserError(`the review record is invalid: ${v0.problems.join('; ')}`);
4632
+ if (!v0.passing) throw new UserError(`the review says verdict ${rec.verdict} — a grant carrying a failing review is a contradiction; nothing was posted`);
4633
+
4634
+ if (!isGhUsable(repoAbs)) {
4635
+ 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`);
4636
+ }
4637
+
4638
+ const info = git.ghIssueView(repoAbs, num, ['state', 'labels', 'title']);
4639
+ if (!info) throw new UserError(`could not read #${num} from the tracker — refusing to write a grant blind`);
4640
+ if (info.state !== 'OPEN') throw new UserError(`#${num} is ${info.state} — a grant expires the instant its issue closes`);
4641
+ if (!ciGrant.titleIsTrunkRed(info.title)) {
4642
+ 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`);
4643
+ }
4644
+ const present = git.ghListLabels(repoAbs);
4645
+ if (present && !present.includes(labels.CI_GRANT_LABEL)) {
4646
+ throw new UserError(labels.ciGrantMissingLabelHint(present) || `this repo has no \`${labels.CI_GRANT_LABEL}\` label`);
4647
+ }
4648
+
4649
+ // Trunk red, in ship's sense — the identical classification cmdCiGrantCreate uses (#155).
4650
+ git.git(['fetch', git.remoteFor(repoAbs), trunk], repoAbs);
4651
+ const trunkRun = git.ghRunForSha(repoAbs, trunk);
4652
+ if (!trunkRun) throw new UserError(`could not read ${trunk}'s CI status (gh run list failed) — refusing to grant blind`);
4653
+ const trunkVerdict = classifyCiRun(repoAbs, trunkRun, `${trunk}@${shortSha(trunkRun.sha)}`);
4654
+ if (trunkVerdict.class !== HUMAN_GATED) {
4655
+ throw new UserError(`${trunk} is not red in the sense \`ship\` checks — ${trunkVerdict.detail || 'green'}. Nothing for a grant to exempt.`);
4656
+ }
4657
+ const redSha = trunkRun.sha;
4658
+ const stacking = computeAntiStacking(repoAbs, trunk, true);
4659
+ if (!stacking.ok) throw new UserError(stacking.reason);
4660
+
4661
+ // The branch's own CI, green at the EXACT head the review covers.
4662
+ const evRun = git.ghRunForSha(repoAbs, opts.branch);
4663
+ if (!evRun) throw new UserError(`could not read "${opts.branch}"'s CI status (gh run list failed) — refusing to grant blind`);
4664
+ if (String(evRun.sha || '').toLowerCase() !== head) {
4665
+ 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`);
4666
+ }
4667
+ if (!(evRun.status === 'completed' && evRun.conclusion === 'success')) {
4668
+ 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`);
4669
+ }
4670
+
4671
+ // Every claimed cure is a red check on trunk at the red sha.
4672
+ const redRunJobs = trunkRedRunJobs(repoAbs, trunk, redSha);
4673
+ const redJobs = redRunJobs === null ? null : ciCure.redJobSet(redRunJobs);
4674
+ const cr = ciGrant.curesAreRed(ciGrant.parseCures(rec.cures), redJobs);
4675
+ if (!cr.ok) throw new UserError(`${cr.reason}; nothing was posted`);
4676
+
4677
+ rec.red = redSha.toLowerCase();
4678
+ const v = ciGrant.validateReviewRecord(rec);
4679
+ if (!v.passing) throw new UserError(`the review record is invalid: ${v.problems.join('; ')}`);
4680
+
4681
+ const editR = git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({}));
4682
+ if (!editR.ok) throw new UserError(`gh edit #${num} failed (${editR.stderr.split('\n')[0] || editR.code})`);
4683
+ const commentR = git.ghIssueComment(repoAbs, num,
4684
+ ciGrant.reviewGrantCommentBody(opts.branch, trunk, commentHost(repoAbs), nowISO(), rec));
4685
+ if (!commentR.ok) {
4686
+ git.ghIssueEdit(repoAbs, num, labels.ciGrantLabelArgs({ clear: true }));
4687
+ 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.`);
4688
+ }
4689
+
4690
+ print(`Recorded a ${ciGrant.REVIEWER_ROLE} CI grant on #${num} in ${shortRepo(repoAbs)} — reviewer "${rec.reviewer}", branch "${opts.branch}" @ ${head.slice(0, 12)}.`);
4691
+ print(` Bound to that HEAD and to red ${trunk}@${shortSha(redSha)}: a new commit on either voids it. Cures: ${rec.cures}.`);
4692
+ if (rec['not-before']) print(` Not usable before ${rec['not-before']} (revoke window).`);
4693
+ print(` Revoke any time: COLAB_HUMAN=1 colab ci-grant ${num} --revoke`);
4694
+ return 0;
4695
+ }
4696
+
4290
4697
  function cmdCiGrantCreate(repoAbs, num, opts) {
4291
4698
  if (!opts.branch) {
4292
4699
  throw new UserError('--branch <branch> is required — a grant is bound to one branch, never inferred from the current checkout');
@@ -4367,7 +4774,8 @@ function cmdCiGrantRevoke(repoAbs, num) {
4367
4774
  if (!info) throw new UserError(`could not read #${num} from the tracker`);
4368
4775
  const labelNames = (info.labels || []).map((l) => (l && typeof l === 'object' ? l.name : l));
4369
4776
  const hasLabel = labelNames.includes(labels.CI_GRANT_LABEL);
4370
- const live = ciGrant.liveGrants(info.comments);
4777
+ // Every role (#504): a revoke cancels reviewer grants too, so a reviewer-only issue is not "nothing to revoke".
4778
+ const live = ciGrant.liveGrantRecords(info.comments);
4371
4779
 
4372
4780
  if (!hasLabel && live.length === 0) {
4373
4781
  print(`No live CI grant on #${num} in ${shortRepo(repoAbs)} — nothing to revoke.`);
@@ -4393,7 +4801,7 @@ function cmdCiGrantRevoke(repoAbs, num) {
4393
4801
  }
4394
4802
 
4395
4803
  function cmdCiGrantList(opts) {
4396
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
4804
+ const repoAbs = resolveRepoOrCwd(opts);
4397
4805
  if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4398
4806
  if (!isGhUsable(repoAbs)) {
4399
4807
  throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — cannot list CI grants`);
@@ -4413,14 +4821,15 @@ function cmdCiGrantList(opts) {
4413
4821
  const stale = [];
4414
4822
  for (const h of hits) {
4415
4823
  const info = git.ghIssueView(repoAbs, h.number, ['state', 'labels', 'comments']);
4416
- const live = info ? ciGrant.liveGrants(info.comments) : [];
4824
+ const live = info ? ciGrant.liveGrantRecords(info.comments) : [];
4417
4825
  if (live.length === 0) { stale.push(h.number); continue; }
4418
4826
  const g = live[live.length - 1];
4419
4827
  // Spent: the normal post-ship state — trunk's head has moved past the sha this grant named.
4420
4828
  // Not an error, just informative — distinguishes "still live, awaiting a ship" from "already
4421
4829
  // used (or overtaken by an unrelated trunk change) and inert" without anyone revoking it.
4422
4830
  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 });
4831
+ const reviewer = g.role !== 'human' ? { role: g.role, reviewer: g.reviewer, head: g.head } : {};
4832
+ 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
4833
  }
4425
4834
 
4426
4835
  if (opts.json) {
@@ -4432,7 +4841,7 @@ function cmdCiGrantList(opts) {
4432
4841
  return 0;
4433
4842
  }
4434
4843
  print(table(
4435
- grants.map((g) => [String(g.issue), g.branch, shortSha(g.redSha), g.spent ? 'spent' : 'live', g.by || '(unknown)', g.title]),
4844
+ 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
4845
  ['ISSUE', 'BRANCH', 'RED SHA', 'STATE', 'GRANTED BY', 'TITLE'],
4437
4846
  ));
4438
4847
  if (stale.length) {
@@ -4500,8 +4909,11 @@ function syncClaims({ prune = false } = {}) {
4500
4909
  if (!git.ghAvailable()) { warn('gh not available — --sync skipped'); return; }
4501
4910
  const st = state.loadState();
4502
4911
  // 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());
4912
+ // #487: every repo here is a MAIN root. This was the writer of the worktree-keyed rows nothing could
4913
+ // release: from inside a linked worktree, repoRoot(cwd) is the worktree, so every assigned issue
4914
+ // was re-added as `<worktree>#N` — a second row beside the real `<mainRoot>#N`, outliving the dir.
4915
+ const repos = new Set(Object.values(st.claims).map((c) => claimHomeRoot(c.repo)).filter(Boolean));
4916
+ const cur = git.mainRepoRoot(process.cwd());
4505
4917
  if (cur) repos.add(cur);
4506
4918
 
4507
4919
  const added = [], removed = [];
@@ -4528,7 +4940,7 @@ function syncClaims({ prune = false } = {}) {
4528
4940
  }
4529
4941
  // local → GH: REMOVE stale local claims ONLY when --prune is given
4530
4942
  if (prune) {
4531
- const localForRepo = Object.entries(st.claims).filter(([k]) => k.startsWith(`${repoAbs}#`));
4943
+ const localForRepo = Object.entries(st.claims).filter(([k]) => claimKeyInRepo(k, repoAbs));
4532
4944
  for (const [key, c] of localForRepo) {
4533
4945
  const num = normIssueNum(c.issue);
4534
4946
  if (!assignedSet.has(num)) {
@@ -4661,7 +5073,7 @@ function cmdPortAlloc(argv) {
4661
5073
  const config = state.loadConfig();
4662
5074
  const count = opts.count ? parseInt(opts.count, 10) : 1;
4663
5075
  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);
5076
+ const explicitRepo = resolveRepoOrCwd(opts);
4665
5077
  const atPorts = parseAtPorts(opts);
4666
5078
 
4667
5079
  // For range resolution, a --worktree owner's repo wins over cwd (its project.yml window applies).
@@ -4708,7 +5120,7 @@ function cmdPortFree(argv) {
4708
5120
  flags: { '-h': 'help', '--help': 'help' },
4709
5121
  });
4710
5122
  if (opts.help) return print(HELP_PORT);
4711
- const repoAbs = opts.repo ? resolveRepo(opts) : (git.repoRoot(process.cwd()) || null);
5123
+ const repoAbs = resolveRepoOrCwd(opts);
4712
5124
 
4713
5125
  const freed = state.mutate((st) => {
4714
5126
  let targets = [];
@@ -4985,7 +5397,10 @@ function removeWorktreeDir(repoAbs, wtPath) {
4985
5397
  function uncommittedWork(wtPath) {
4986
5398
  if (!wtPath || !fs.existsSync(wtPath)) return { any: false, lines: '', what: '' };
4987
5399
  const tracked = git.dirtyTracked(wtPath);
4988
- const untracked = git.dirtyUntracked(wtPath);
5400
+ // #488: scratch (a plan or brief left in the worktree) is disposable by definition — it must never
5401
+ // be what makes a teardown refuse. Normally info/exclude already hides it; this covers a clone
5402
+ // whose exclude predates the scratch dirs, or a dir configured after the worktree was cut.
5403
+ const untracked = scratchDirs.withoutScratch(git.dirtyUntracked(wtPath));
4989
5404
  return {
4990
5405
  any: !!(tracked || untracked),
4991
5406
  lines: [tracked, untracked].filter(Boolean).join('\n'),
@@ -5260,6 +5675,10 @@ function cmdWorktreeNew(argv) {
5260
5675
  }
5261
5676
  settleTrackerPending(repoAbs, claimedHere.filter((n) => !lostIssues.includes(n)), trackerMissed, { wtName: name, branch });
5262
5677
 
5678
+ // #488: the scratch dirs (plans, briefs) are hidden in the clone's shared info/exclude — one
5679
+ // write covers the main checkout and every worktree, with no per-repo .gitignore diff.
5680
+ ensureScratchExcluded(repoAbs);
5681
+
5263
5682
  // 5. optional repo hook (machine-specific steps plug in here)
5264
5683
  const hook = runHook(repoAbs, 'post-create', { wtPath, name, branch, ports: alloc.chosenPorts, trunk, base, issues });
5265
5684
  if (hook.ran && !hook.ok) warn(`post-create hook exited ${hook.code} — worktree was still created; finish setup manually`);
@@ -6231,9 +6650,15 @@ function cmdDoctor(argv) {
6231
6650
  const entry = { repo: shortRepo(repo), label: v.name, verdict: v.verdict,
6232
6651
  total: v.total, open: v.open, members: v.members, deleted: false, error: null };
6233
6652
  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';
6653
+ // #448: `spent` came from the search-backed listing; confirm through the issues table.
6654
+ const t = groupLabels.teardownSpentGroupLabel(v.name, {
6655
+ searchOpen: [],
6656
+ confirmOpen: (name) => git.ghOpenIssueNumbersByLabel(repo, name),
6657
+ deleteLabel: (name) => git.ghLabelDelete(repo, name),
6658
+ });
6659
+ entry.deleted = t.deleted;
6660
+ if (t.action === 'keep') entry.error = groupLabels.keptReason(v.name, t);
6661
+ else if (!t.deleted) entry.error = t.error;
6237
6662
  }
6238
6663
  report.spentGroupLabels.push(entry);
6239
6664
  }
@@ -6725,9 +7150,10 @@ function measureHeadCandidate(repoAbs, { candidatesAuto, mainRef, lastRelease, o
6725
7150
  const tagsAtSha = tagsR.ok ? tagsR.stdout.split('\n').map((t) => t.trim()).filter(Boolean) : [];
6726
7151
  let runs = null;
6727
7152
  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; } }
7153
+ const r = tracker.forRepo(repoAbs).runList({
7154
+ branch: 'main', commit: sha, limit: 50, fields: ['status', 'conclusion', 'event', 'createdAt', 'updatedAt', 'workflowName'],
7155
+ });
7156
+ runs = Array.isArray(r.data) ? r.data : null;
6731
7157
  }
6732
7158
  const promotion = dualTrunk ? measurePromotion(repoAbs, { sha, trunk, remote, fetched: fetchTrunk }) : null;
6733
7159
  return releaseCut.headCandidateVerdict({
@@ -6763,7 +7189,9 @@ Per tag-gated repo:
6763
7189
  headCandidate #443, where candidates are automatic: { state, flag, detail } — whether the newest
6764
7190
  candidate names main's head. Flags (state untagged, "head not a candidate") when
6765
7191
  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 ·
7192
+ sha — and carries no tag. Also flags (state no-final, #467) when there is no final tag
7193
+ at all: \`release cut --auto\` refuses every run until a human tags the first version,
7194
+ a stall that otherwise reads green. Other states: named · nothing-owed · not-green ·
6767
7195
  pending (inside one cycle) · not-promotion (trunk: dev, a hotfix head) · unread · off.
6768
7196
  semverSuggestion from Conventional-Commit types since the last tag: a breaking change (! or a
6769
7197
  BREAKING CHANGE: footer) -> major, else feat -> minor, else fix -> patch,
@@ -6775,7 +7203,7 @@ fetch failure does not abort the row — it degrades to whatever is on disk and
6775
7203
  rather than reporting nothing.
6776
7204
 
6777
7205
  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.
7206
+ 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
7207
  `;
6780
7208
 
6781
7209
  function cmdReleaseStatus(argv) {
@@ -6824,7 +7252,7 @@ function cmdReleaseStatus(argv) {
6824
7252
  const tableRows = printable.map((r) => {
6825
7253
  const up = r.unpromoted ? `${r.unpromoted.commits}${r.unpromoted.fixFlag ? ' ⚠' : ''}` : '—';
6826
7254
  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) : '—';
7255
+ const hc = r.headCandidate ? (r.headCandidate.flag ? (r.headCandidate.state === 'no-final' ? '⚠ no final' : '⚠ not a candidate') : r.headCandidate.state) : '—';
6828
7256
  return [r.repo, up, un, hc, r.semverSuggestion.bump || '—', r.flag ? '⚠ FLAGGED' : ''];
6829
7257
  });
6830
7258
  print(table(tableRows, ['REPO', 'UNPROMOTED', 'UNRELEASED', 'HEAD', 'SUGGEST', '']));
@@ -6841,7 +7269,7 @@ function cmdReleaseStatus(argv) {
6841
7269
  }
6842
7270
  print('');
6843
7271
  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:`);
7272
+ 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
7273
  for (const r of flagged) print(` ${r.repo}${r.headCandidate && r.headCandidate.flag ? ` — ${r.headCandidate.detail}` : ''}`);
6846
7274
  print('Who cuts the tag follows the release rung of CONVENTIONS §6 — this only measures the gap.');
6847
7275
  } else {
@@ -7287,6 +7715,7 @@ const HELP_ADOPT = `colab adopt [--repo <path>] [--json] [--no-verify] [--axis a
7287
7715
  [--writes <free|direct|isolated>] [--channels <c1,c2,...>]
7288
7716
  [--production <url>|none] [--deploy <push-main|tag|manual|none>]
7289
7717
  [--stack "<text>"] [--answered-by <name>] [--reason "<text>"]
7718
+ [--fork | --no-fork] [--autonomy <manual|auto-trunk>] [--land]
7290
7719
 
7291
7720
  Detects what a repo already states in .github/project.yml, ASKS a human only what could not be
7292
7721
  detected (flags, or a forced multiple-choice menu at a TTY — every row is a numbered choice,
@@ -7294,6 +7723,18 @@ answered by its number OR its literal value), DERIVES the rest, and WRITES the d
7294
7723
  act — append-only, never touching a byte already there. A complete descriptor just reports
7295
7724
  (write nothing, exit 0); re-answer one row on purpose with --axis.
7296
7725
 
7726
+ ONLY THE GATING ROWS ARE ASKED (#533): deploy/production and exposure. room, writes and channels
7727
+ are optional and legal absent — never prompted for; the report names them in one line with the
7728
+ \`--axis\` command that answers each later, and their own flag still answers one in the same run.
7729
+ After deploy: none, production is not asked again (null follows; --deploy none alone implies it).
7730
+
7731
+ A SINGLE TRUNK, ANY SPELLING (#522): exposure none (and released with production null, and the
7732
+ legacy tier B) need ONE long-lived branch, not one named "main" — an existing master default
7733
+ adopts as-is. A "main" beside a non-main trunk is the two-branch shape and is refused (exit 5).
7734
+ At a terminal the exposure answer is checked against that shape when given, and re-asked with
7735
+ the reason. When a human must finish (the gate below), the FIRST line printed is the one
7736
+ command to run, every answer this run had already filled in.
7737
+
7297
7738
  --writes accepts free (coexistence, the default), direct (an attended human may commit straight
7298
7739
  to trunk; DECLARED today, its runtime is DEFERRED — see CONVENTIONS.md §2, "writes: direct —
7299
7740
  declared today, runtime deferred"), or isolated (vetoes trunk-direct outright, human or not).
@@ -7308,8 +7749,41 @@ accepted and reads as free — no adopter's descriptor breaks, and none is re-as
7308
7749
  --answered-by N who is answering, alongside COLAB_HUMAN=1 (see THE HUMAN GATE below)
7309
7750
  --reason "..." required alongside a lowered or evidence-contradicted exposure answer;
7310
7751
  written into the file, next to the key it justifies
7311
-
7312
- Any answer flag (--room/--exposure/--writes/--channels/--production/--deploy/--stack) makes the
7752
+ --fork / --no-fork
7753
+ a repo you own that tracks an upstream you don't (#449) is DETECTED — a
7754
+ remote named \`upstream\` whose URL differs from origin's. Assert it with
7755
+ --fork when the upstream remote is named otherwise; deny it with --no-fork.
7756
+ On a fork, step 5 of the remaining list is the append-only Conventions block
7757
+ (never the thin-shell conversion), the upstream's own agent workflow is
7758
+ named, and a new CLAUDE.md gets no AGENTS.md stub (CONVENTIONS.md §9,
7759
+ "A fork of an upstream")
7760
+
7761
+ THE AUTONOMY GRANT AND --land (#481) — so a new repo's first branch is not hand-merged:
7762
+
7763
+ --autonomy auto-trunk records the maintainer's grant (project.yml autonomy:) with the same
7764
+ provenance comment as every answer. It EXPANDS permission (an agent may
7765
+ then complete Phase B through \`colab ship\`), so it carries the writes:
7766
+ direct bar: interactive TTY, OR COLAB_HUMAN=1 AND --answered-by <name>
7767
+ (exit 3 otherwise). Refused with ceremony: light (exit 5). manual (the
7768
+ default) is never gated. Append-only: a different value already declared
7769
+ is refused (exit 5) — change it by hand.
7770
+ --land commits what THIS run wrote — the descriptor, plus the thin-shell
7771
+ CLAUDE.md/AGENTS.md when written now — straight to trunk as its own
7772
+ commit, then pushes origin/<trunk>. It is the human's adoption act, not
7773
+ an agent's: COLAB_HUMAN=1 AND --answered-by are required, no TTY
7774
+ substitute (exit 3). It runs only on the checkout standing ON trunk, never
7775
+ with --local, and refuses before writing anything when origin's trunk is
7776
+ ahead (pull first). Run without new answers, it lands a descriptor an
7777
+ earlier adopt left uncommitted. No origin remote: commits only.
7778
+
7779
+ The shape it exists for: \`colab ship\` judges a branch's autonomy by the descriptor trunk
7780
+ carries. Land it first, and the follow-up branch (CI workflow, guards, docs) ships through the
7781
+ normal lane under the grant — no human merge of the adoption branch.
7782
+
7783
+ COLAB_HUMAN=1 colab adopt --exposure self --stack node --autonomy auto-trunk \\
7784
+ --answered-by "<name>" --land
7785
+
7786
+ Any answer flag (--room/--exposure/--writes/--channels/--production/--deploy/--stack/--autonomy) makes the
7313
7787
  whole run NON-INTERACTIVE — it never half-prompts. With no answer flags and no TTY, and something
7314
7788
  is still missing, this refuses in under a second, naming exactly which flags would answer it —
7315
7789
  never hangs waiting on stdin nobody is at.
@@ -7399,7 +7873,8 @@ files is not an option (CONVENTIONS.md §9, "Working in a repo you don't own"):
7399
7873
 
7400
7874
  1. refuses if .github/project.yml is TRACKED (then the repo is adopted — use plain adopt), if
7401
7875
  --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
7876
+ 2. appends /.github/project.yml, /CLAUDE.local.md, the scratch dirs (/.plans/, /.briefs/,
7877
+ legacy /.claude/plans/ — #488) and the worktree subdir
7403
7878
  (/.worktrees/ by default — the owner's .gitignore does not hide it) to .git/info/exclude (the
7404
7879
  shared common dir — never .gitignore, which is itself a tracked file) BEFORE writing, and
7405
7880
  keeps them even if a later check refuses (idempotent, local, hides nothing that exists);
@@ -7415,7 +7890,7 @@ files is not an option (CONVENTIONS.md §9, "Working in a repo you don't own"):
7415
7890
  block, topic, register, autopilot) and why.
7416
7891
 
7417
7892
  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
7893
+ \`colab register\`, and it never commits unless --land asks it to (#481). One exception (#417): on a repo with no descriptor before
7419
7894
  the run and no CLAUDE.md, plain adopt also writes the thin-shell CLAUDE.md (\`@AGENTS.md\` + the
7420
7895
  filled Conventions block) and an AGENTS.md stub if none exists; an existing CLAUDE.md is never
7421
7896
  touched, and --local never writes either. It ends with the machine-readable
@@ -7436,7 +7911,7 @@ const ADOPT_ROW_ORDER = ['tier', 'room', 'exposure', 'writes', 'channels'];
7436
7911
  * read from a remote's HEAD, and the report says so (`detected.trunk.source`), never presented
7437
7912
  * as though it were.
7438
7913
  */
7439
- function adoptGitExtras(repoAbs) {
7914
+ function adoptGitExtras(repoAbs, opts = {}) {
7440
7915
  let trunk = git.detectTrunk(repoAbs);
7441
7916
  let trunkSource = trunk ? 'origin-head' : null;
7442
7917
  if (!trunk) {
@@ -7450,7 +7925,48 @@ function adoptGitExtras(repoAbs) {
7450
7925
  const hooksPath = hp.ok && hp.stdout ? hp.stdout : null;
7451
7926
  let hooksDirFiles = [];
7452
7927
  try { hooksDirFiles = fs.readdirSync(path.join(repoAbs, '.githooks')); } catch (_) { /* absent */ }
7453
- return { trunk, trunkSource, hooksPath, hooksDirFiles };
7928
+ // #449: `git ls-files` for the migrations candidate scan (adopt never asks `migrations:`).
7929
+ const ls = git.git(['ls-files'], repoAbs);
7930
+ const trackedFiles = ls.ok ? ls.stdout.split('\n').filter(Boolean) : undefined;
7931
+ // #483: the fork's own owner, from origin's URL — what an inherited CODEOWNERS team is compared to.
7932
+ const originUrl = git.git(['remote', 'get-url', 'origin'], repoAbs);
7933
+ const ownOrg = originUrl.ok ? codeowners.remoteOwner(originUrl.stdout) : null;
7934
+ return { trunk, trunkSource, hooksPath, hooksDirFiles, trackedFiles, fork: adoptDetectFork(repoAbs, opts), ownOrg, branches: adoptBranchList(repoAbs) };
7935
+ }
7936
+
7937
+ /** #522: every branch name visible here — refs/heads ∪ refs/remotes/<any>/<name> — the same union
7938
+ * audit/audit.mjs's `branches()` reads, so the single-trunk rule (tools/lib/exposure-shape.js
7939
+ * `singleTrunkViolation`) answers identically on both sides: adopt never writes what the audit
7940
+ * then fails. null when git cannot list refs (the rule then fails closed to trunk "main"). */
7941
+ function adoptBranchList(repoAbs) {
7942
+ const r = git.git(['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes'], repoAbs);
7943
+ if (!r.ok) return null;
7944
+ const names = new Set();
7945
+ for (const ref of r.stdout.split('\n').map((x) => x.trim()).filter(Boolean)) {
7946
+ if (ref.startsWith('refs/heads/')) names.add(ref.slice('refs/heads/'.length));
7947
+ else if (ref.startsWith('refs/remotes/')) {
7948
+ const rest = ref.slice('refs/remotes/'.length);
7949
+ const name = rest.slice(rest.indexOf('/') + 1);
7950
+ if (rest.includes('/') && name && name !== 'HEAD') names.add(name);
7951
+ }
7952
+ }
7953
+ return [...names];
7954
+ }
7955
+
7956
+ /**
7957
+ * #449 — is this a repo you own that tracks an upstream you don't? DETECTED, never asked (§9):
7958
+ * a remote named `upstream` whose URL differs from origin's (the conventional name for the repo a
7959
+ * fork tracks). `--fork` asserts it when the upstream remote is named otherwise; `--no-fork`
7960
+ * denies it when a remote named `upstream` means something else. Returns null when not a fork.
7961
+ */
7962
+ function adoptDetectFork(repoAbs, opts = {}) {
7963
+ if (opts.noFork) return null;
7964
+ const up = git.git(['remote', 'get-url', 'upstream'], repoAbs);
7965
+ const origin = git.git(['remote', 'get-url', 'origin'], repoAbs);
7966
+ const upUrl = up.ok && up.stdout ? up.stdout : null;
7967
+ if (upUrl && !(origin.ok && origin.stdout === upUrl)) return { remote: 'upstream', url: upUrl, source: opts.fork ? 'flag' : 'upstream-remote' };
7968
+ if (opts.fork) return { remote: null, url: null, source: 'flag' };
7969
+ return null;
7454
7970
  }
7455
7971
 
7456
7972
  /** The `{ readFile, listDir, tags }` adapter tools/lib/adopt.js asks for — matching the local
@@ -7504,6 +8020,26 @@ function gitExcludePath(repoAbs) {
7504
8020
  return path.join(r.stdout, 'info', 'exclude');
7505
8021
  }
7506
8022
 
8023
+ /**
8024
+ * #488: append the scratch-dir exclude lines (scratch-dirs.js `excludeLines`) to the clone's shared
8025
+ * info/exclude, idempotently. Best-effort: a failure warns and never blocks the caller.
8026
+ */
8027
+ function ensureScratchExcluded(repoAbs) {
8028
+ const excludeFile = gitExcludePath(repoAbs);
8029
+ if (!excludeFile) return [];
8030
+ let before = null;
8031
+ try { before = fs.readFileSync(excludeFile, 'utf8'); } catch (_) { /* absent */ }
8032
+ const lines = scratchDirs.excludeLines();
8033
+ const missing = localAdopt.missingExcludeLines(before, lines);
8034
+ if (!missing.length) return [];
8035
+ try {
8036
+ fs.mkdirSync(path.dirname(excludeFile), { recursive: true });
8037
+ const sep = before && !before.endsWith('\n') ? '\n' : '';
8038
+ fs.appendFileSync(excludeFile, sep + missing.join('\n') + '\n');
8039
+ } catch (e) { warn(`could not hide the scratch dirs in ${excludeFile}: ${e.message}`); return []; }
8040
+ return missing;
8041
+ }
8042
+
7507
8043
  function gitTracks(repoAbs, rel) {
7508
8044
  return git.git(['ls-files', '--error-unmatch', '--', rel], repoAbs).ok;
7509
8045
  }
@@ -7687,6 +8223,15 @@ function printAdoptReport(report, repoAbs, verify, localFinish) {
7687
8223
  print(`detected trunk: ${t.detected || '(unknown)'}${trunkSourceNote}${t.declared !== null ? ` (declared: ${t.declared}${t.agree === false ? ' ⚠ disagrees with detected' : ''})` : ''}`);
7688
8224
  print(`stack candidates: ${report.detected.stackCandidates.length ? report.detected.stackCandidates.join(', ') : '(none found)'}`);
7689
8225
  print(`declared ports: ${fmtVal(report.detected.ports)}`);
8226
+ const optLine = adopt.optionalRowsLine(report.optionalUnanswered); // #533
8227
+ if (optLine) print(optLine);
8228
+ 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")`);
8229
+ if (report.inheritedCodeowners) {
8230
+ const ic = report.inheritedCodeowners;
8231
+ print(`⚠ inherited CODEOWNERS: ${ic.path} names ${ic.teams.join(', ')} — team(s) of an org other than ${ic.ownOrg}. ` +
8232
+ 'colab ship ignores them on this fork, so they gate no landing here; write the fork\'s own owners into that file ' +
8233
+ '(a fork patch) if some paths here should need a review (§2 "Core paths", #483)');
8234
+ }
7690
8235
  print(`legacy tier letter, derived from (production, deploy): ${report.legacyTierLetter ?? '(undetermined — production is set but deploy matches none of push-main/tag/manual)'}`);
7691
8236
  print('');
7692
8237
  print('Derived consequences:');
@@ -7755,6 +8300,8 @@ function adoptAnswersFromFlags(opts, cfg, axesToAsk, forcedAxes) {
7755
8300
  if (!adopt.VALID_DEPLOY.has(opts.deploy)) throw new UserError(`--deploy must be one of: ${[...adopt.VALID_DEPLOY].join(', ')}`);
7756
8301
  values.deploy = opts.deploy;
7757
8302
  flags.push('--deploy');
8303
+ // #533: deploy: none already says nothing is live — production: null follows, never re-asked.
8304
+ if (opts.deploy === 'none' && opts.production === undefined && eligible('production', 'tier')) values.production = null;
7758
8305
  }
7759
8306
  if (flags.length) answers.tier = { values, mode: 'flag', flags };
7760
8307
  }
@@ -7818,7 +8365,7 @@ async function askMenu(rl, axis, promptFn) {
7818
8365
  * URL itself asked only on "yes" — this keeps every axis forced-choice-shaped without pretending
7819
8366
  * a URL belongs to an enum.
7820
8367
  */
7821
- async function adoptAskInteractive(rl, axesToAsk, cfg) {
8368
+ async function adoptAskInteractive(rl, axesToAsk, cfg, checkExposure) {
7822
8369
  const answers = {};
7823
8370
  for (const axis of axesToAsk) {
7824
8371
  const q = adopt.QUESTIONS.find((x) => x.axis === axis);
@@ -7829,13 +8376,16 @@ async function adoptAskInteractive(rl, axesToAsk, cfg) {
7829
8376
  process.stdout.write(`${adopt.renderMenu('tier')}\n`);
7830
8377
  return rlAsk(rl, ' deploy: ');
7831
8378
  });
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
8379
  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)');
8380
+ // #533: deploy: none already answered "nothing is live" — asking production again is noise.
8381
+ if (depChoice.value !== 'none') {
8382
+ process.stdout.write(' 1) no deploy target exists today\n 2) yes — enter the URL\n');
8383
+ const existsRaw = (await rlAsk(rl, ' production: ')).trim();
8384
+ if (existsRaw === '2' || existsRaw === 'yes') {
8385
+ prod = (await rlAsk(rl, ' URL: ')).trim() || null;
8386
+ } else if (existsRaw !== '1' && existsRaw !== 'no') {
8387
+ throw new UserError('production: choose 1 (no deploy target exists today) or 2 (yes — enter the URL)');
8388
+ }
7839
8389
  }
7840
8390
  answers.tier = { values: { production: prod, deploy: depChoice.value }, mode: 'interactive' };
7841
8391
  } else if (axis === 'channels') {
@@ -7845,12 +8395,22 @@ async function adoptAskInteractive(rl, axesToAsk, cfg) {
7845
8395
  });
7846
8396
  answers.channels = { values: { channels: resolved.value }, mode: 'interactive' };
7847
8397
  } 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' };
8398
+ // #522: the repo-shape check runs HERE, at answer time — a refusal re-asks with its reason,
8399
+ // instead of surfacing after every other question with nothing written.
8400
+ let chosen = null;
8401
+ for (let attempt = 0; attempt < 2 && !chosen; attempt++) {
8402
+ const resolved = await askMenu(rl, 'exposure', () => {
8403
+ process.stdout.write(`${adopt.renderMenu('exposure')}\n`);
8404
+ return rlAsk(rl, ' choice: ');
8405
+ });
8406
+ if (resolved.skip) { chosen = resolved; break; }
8407
+ const problem = checkExposure ? checkExposure(resolved.value, answers) : null;
8408
+ if (!problem) { chosen = resolved; break; }
8409
+ process.stdout.write(` ✗ ${problem}\n choose again (or skip):\n`);
8410
+ }
8411
+ if (!chosen) throw new UserError('exposure: no answer this repo\'s shape supports after one re-prompt');
8412
+ if (chosen.skip) continue; // decline — the fallback tier derivation picks this up
8413
+ answers.exposure = { values: { exposure: chosen.value }, mode: 'interactive' };
7854
8414
  } else {
7855
8415
  // room, writes — plain single-choice menus, no skip.
7856
8416
  const resolved = await askMenu(rl, axis, () => {
@@ -7863,11 +8423,41 @@ async function adoptAskInteractive(rl, axesToAsk, cfg) {
7863
8423
  return answers;
7864
8424
  }
7865
8425
 
8426
+ /** #522: this run's answers as the ordered flag list `adopt.humanAdoptCommand` prints — what the
8427
+ * human pastes to finish the same adoption with the gate satisfied. */
8428
+ function adoptReplayFlags(opts, answers) {
8429
+ const flags = [];
8430
+ if (opts.repo !== undefined) flags.push(['--repo', opts.repo]);
8431
+ const t = answers.tier && answers.tier.values;
8432
+ if (t && 'production' in t) flags.push(['--production', t.production === null ? 'none' : t.production]);
8433
+ if (t && 'deploy' in t) flags.push(['--deploy', t.deploy]);
8434
+ if (answers.exposure) flags.push(['--exposure', answers.exposure.values.exposure]);
8435
+ if (answers.room) flags.push(['--room', answers.room.values.room]);
8436
+ if (answers.writes) flags.push(['--writes', answers.writes.values.writes]);
8437
+ if (answers.channels) flags.push(['--channels', answers.channels.values.channels.join(',')]);
8438
+ if (opts.stack !== undefined) flags.push(['--stack', opts.stack]);
8439
+ if (opts.autonomy !== undefined) flags.push(['--autonomy', opts.autonomy]);
8440
+ if (opts.reason !== undefined) flags.push(['--reason', opts.reason]);
8441
+ if (opts.answeredBy) flags.push(['--answered-by', opts.answeredBy]);
8442
+ if (opts.land) flags.push(['--land', true]);
8443
+ return flags;
8444
+ }
8445
+
8446
+ /** #522: the same command shape for a run that had no answers at all — placeholders per asked row. */
8447
+ function adoptAskedFlagPlaceholders(axesToAsk, stackUnresolvable) {
8448
+ const flags = [];
8449
+ if (axesToAsk.includes('tier')) flags.push(['--production', '<url>|none'], ['--deploy', '<none|tag|manual|push-main>']);
8450
+ if (axesToAsk.includes('exposure')) flags.push(['--exposure', '<none|self|live|released>']);
8451
+ for (const a of ['room', 'writes', 'channels']) if (axesToAsk.includes(a)) flags.push([`--${a}`, `<${a}>`]);
8452
+ if (stackUnresolvable) flags.push(['--stack', '<text>']);
8453
+ return flags;
8454
+ }
8455
+
7866
8456
  /** The `EXPOSURE_SHAPE`/falsifier context, built from EFFECTIVE production/deploy — accounting
7867
8457
  * for a `tier`-axis answer resolved in THIS SAME run, not only what was already on record, so
7868
8458
  * declaring production+deploy and exposure together in one invocation validates against each
7869
8459
  * other rather than the pre-write snapshot. */
7870
- function adoptShapeCtx(cfg, tierAnswer, trunk, workflows, io) {
8460
+ function adoptShapeCtx(cfg, tierAnswer, trunk, workflows, io, branches) {
7871
8461
  const effProduction = tierAnswer ? tierAnswer.values.production : (Object.prototype.hasOwnProperty.call(cfg, 'production') ? cfg.production : null);
7872
8462
  const effDeploy = tierAnswer ? tierAnswer.values.deploy : (Object.prototype.hasOwnProperty.call(cfg, 'deploy') ? cfg.deploy : null);
7873
8463
  const evidence = consumerEvidence.consumerEvidence(io, workflows);
@@ -7875,7 +8465,7 @@ function adoptShapeCtx(cfg, tierAnswer, trunk, workflows, io) {
7875
8465
  const hasProduction = effProduction !== null && effProduction !== undefined && effProduction !== '';
7876
8466
  const runbook = Object.prototype.hasOwnProperty.call(cfg, 'runbook') ? cfg.runbook : null;
7877
8467
  const hasRunbook = !!(runbook && io.readFile(String(runbook).trim().replace(/^\.\//, '')) !== null);
7878
- return { trunk, hasProduction, deploy: effDeploy, hasDeployWorkflow, hasRunbook, effProduction, effDeploy };
8468
+ return { trunk, hasProduction, deploy: effDeploy, hasDeployWorkflow, hasRunbook, effProduction, effDeploy, branches: branches === undefined ? null : branches };
7879
8469
  }
7880
8470
 
7881
8471
  async function cmdAdopt(argv) {
@@ -7884,15 +8474,20 @@ async function cmdAdopt(argv) {
7884
8474
  '--repo': 'repo', '--axis': 'axis', '--room': 'room', '--exposure': 'exposure',
7885
8475
  '--writes': 'writes', '--channels': 'channels', '--production': 'production',
7886
8476
  '--deploy': 'deploy', '--stack': 'stack', '--answered-by': 'answeredBy', '--reason': 'reason',
7887
- '--trunk': 'trunk',
8477
+ '--trunk': 'trunk', '--autonomy': 'autonomy',
7888
8478
  },
7889
- flags: { '--json': 'json', '--no-verify': 'noVerify', '--local': 'local', '--no-labels': 'noLabels', '-h': 'help', '--help': 'help' },
8479
+ flags: { '--json': 'json', '--no-verify': 'noVerify', '--local': 'local', '--no-labels': 'noLabels', '--fork': 'fork', '--no-fork': 'noFork', '--land': 'land', '-h': 'help', '--help': 'help' },
7890
8480
  });
7891
8481
  if (opts.help) return print(HELP_ADOPT);
8482
+ if (opts.fork && opts.noFork) throw new UserError('--fork and --no-fork contradict each other — pass one');
7892
8483
  if (opts.trunk !== undefined && !opts.local) {
7893
8484
  throw new UserError('--trunk only means something with --local — on an ordinary adoption trunk is DETECTED, never asked (CONVENTIONS.md §9)');
7894
8485
  }
7895
8486
  if (opts.noLabels && !opts.local) throw new UserError('--no-labels only means something with --local — plain adopt never touches labels');
8487
+ if (opts.land && opts.local) throw new UserError('--land cannot combine with --local — a local-only descriptor is never committed (CONVENTIONS.md §9)');
8488
+ if (opts.autonomy !== undefined && !adopt.VALID_AUTONOMY.has(opts.autonomy)) {
8489
+ throw new UserError(`--autonomy must be one of: ${[...adopt.VALID_AUTONOMY].join(', ')} (got ${JSON.stringify(opts.autonomy)})`);
8490
+ }
7896
8491
 
7897
8492
  // --local (#393): the descriptor is machine state, not a committable source file — it lives in
7898
8493
  // the MAIN checkout (where every worktree's `colab` call reads project.yml from, via
@@ -7904,7 +8499,7 @@ async function cmdAdopt(argv) {
7904
8499
  if (local.exit !== undefined) return local.exit;
7905
8500
  }
7906
8501
  const io = adoptIo(repoAbs);
7907
- const extra = adoptGitExtras(repoAbs);
8502
+ const extra = adoptGitExtras(repoAbs, opts);
7908
8503
  if (local) { extra.trunk = local.trunk; extra.trunkSource = 'local-integration'; }
7909
8504
  const report = adopt.detect(io, extra);
7910
8505
  const cfg = report.cfg;
@@ -7916,16 +8511,45 @@ async function cmdAdopt(argv) {
7916
8511
  if (!adopt.ROW_NAMES.includes(a)) throw new UserError(`Unknown --axis "${a}" — expected one of: ${adopt.ROW_NAMES.join(', ')}`);
7917
8512
  }
7918
8513
  const forcedAxes = new Set(requestedAxes);
7919
- let axesToAsk = adopt.ROW_NAMES.filter((a) => forcedAxes.has(a) || adopt.axisMissing(cfg, a));
8514
+ // #533: a fresh adoption asks only the rows that change a gate (production/deploy, exposure);
8515
+ // room/writes/channels are asked only when forced (--axis) or answered by their flag.
8516
+ const flagAxes = new Set();
8517
+ if (opts.production !== undefined || opts.deploy !== undefined) flagAxes.add('tier');
8518
+ for (const a of ['room', 'exposure', 'writes', 'channels']) if (opts[a] !== undefined) flagAxes.add(a);
8519
+ let axesToAsk = adopt.axesToAsk(cfg, forcedAxes, flagAxes);
7920
8520
  // --local re-run (#393): once exposure is on record, a bare `adopt --local` (no answer flags, no
7921
8521
  // --axis) is the idempotent re-apply — exclude lines, stub, labels, checkout — never a prompt for
7922
8522
  // the optional rows (room/writes/channels), which --local leaves to the operator by design.
7923
8523
  const localAnswerFlag = ['room', 'exposure', 'writes', 'channels', 'production', 'deploy', 'stack'].some((k) => opts[k] !== undefined);
7924
8524
  if (local && !localAnswerFlag && !requestedAxes.length && axisAuthority.axisOfRecord(cfg).source === 'exposure') axesToAsk = [];
7925
8525
 
8526
+ const isTTY = !!(process.stdin.isTTY && process.stdout.isTTY);
8527
+ const colabHuman = process.env.COLAB_HUMAN === '1';
8528
+
8529
+ // #481: --land preflight — every refusal here happens BEFORE anything is written, like the gates.
8530
+ let landTrunk = null;
8531
+ if (opts.land) {
8532
+ landTrunk = cfg.trunk ? String(cfg.trunk) : (extra.trunk || null);
8533
+ const cur = git.git(['symbolic-ref', '--short', 'HEAD'], repoAbs);
8534
+ const lv = adopt.landVerdict({ local: !!opts.local, colabHuman, answeredBy: opts.answeredBy || null,
8535
+ trunk: landTrunk, currentBranch: cur.ok && cur.stdout ? cur.stdout : null });
8536
+ if (!lv.ok) { warn(lv.message); return lv.exitCode; }
8537
+ const behind = adoptLandBehind(repoAbs, landTrunk);
8538
+ if (behind) { warn(behind); return 1; }
8539
+ }
8540
+
8541
+ // #481: --autonomy — the maintainer's grant, gated like writes: direct (it expands permission).
8542
+ let autonomyWrite = false;
8543
+ if (opts.autonomy !== undefined) {
8544
+ const av = adopt.autonomyGateVerdict({ autonomy: opts.autonomy, current: cfg.autonomy, ceremony: cfg.ceremony,
8545
+ isTTY, colabHuman, answeredBy: opts.answeredBy || null });
8546
+ if (!av.ok) { warn(av.message); return av.exitCode; }
8547
+ autonomyWrite = av.write;
8548
+ }
8549
+
7926
8550
  // Already complete (and nothing forced): report, write nothing, exit 0 — except the one key a
7927
8551
  // 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) {
8552
+ if (axesToAsk.length === 0 && opts.stack === undefined && !autonomyWrite) {
7929
8553
  const backfill = localOwnerEntry(local, cfg, today());
7930
8554
  if (backfill) {
7931
8555
  fs.writeFileSync(descriptorFile, adopt.renderDescriptor(rawTextBefore, [backfill]));
@@ -7933,9 +8557,12 @@ async function cmdAdopt(argv) {
7933
8557
  }
7934
8558
  const verify = opts.noVerify ? null : adoptVerify(repoAbs);
7935
8559
  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; }
8560
+ const land = opts.land ? adoptLand(repoAbs, landTrunk, ['.github/project.yml'], opts.answeredBy) : undefined;
8561
+ const rc = (lf && !lf.ok) || (land && !land.ok) ? 1 : 0;
8562
+ 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
8563
  printAdoptReport(report, repoAbs, verify, lf);
7938
- return lf && !lf.ok ? 1 : 0;
8564
+ printAdoptLand(land);
8565
+ return rc;
7939
8566
  }
7940
8567
 
7941
8568
  // `trunk` is DETECTED, never asked — no answer flag can supply it, and asking a human "what is
@@ -7950,9 +8577,9 @@ async function cmdAdopt(argv) {
7950
8577
  return 1;
7951
8578
  }
7952
8579
 
7953
- const answerFlagKeys = ['room', 'exposure', 'writes', 'channels', 'production', 'deploy', 'stack'];
8580
+ // --autonomy counts as an answer flag (#481): it makes the run non-interactive, never half-prompted.
8581
+ const answerFlagKeys = ['room', 'exposure', 'writes', 'channels', 'production', 'deploy', 'stack', 'autonomy'];
7954
8582
  const anyAnswerFlagGiven = answerFlagKeys.some((k) => opts[k] !== undefined);
7955
- const isTTY = !!(process.stdin.isTTY && process.stdout.isTTY);
7956
8583
 
7957
8584
  // `stack` is REQUIRED by the audit but free-form, so it cannot always be detected — a
7958
8585
  // manifest-less repo (a docs-only repo; this handbook's own shape) has zero candidates.
@@ -7967,7 +8594,8 @@ async function cmdAdopt(argv) {
7967
8594
  let stackAnsweredInteractively = false;
7968
8595
  if (axesToAsk.length === 0) {
7969
8596
  answers = {};
7970
- } else if (anyAnswerFlagGiven) {
8597
+ } else if (anyAnswerFlagGiven || (opts.land && !isTTY)) {
8598
+ // #481: a bare --land with no terminal lands what is already on disk — it never asks.
7971
8599
  // Fully non-interactive: whatever flags were given get applied; anything still missing
7972
8600
  // just stays missing (reported in "remaining"), never prompted for — half a prompt is worse
7973
8601
  // than none. `stack` is the one exception: it is a required key, not an optional row, so an
@@ -7982,7 +8610,11 @@ async function cmdAdopt(argv) {
7982
8610
  } else if (isTTY) {
7983
8611
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
7984
8612
  try {
7985
- answers = await adoptAskInteractive(rl, axesToAsk, cfg);
8613
+ const shapeWorkflows = io.listDir('.github/workflows').filter((f) => /\.ya?ml$/.test(f));
8614
+ answers = await adoptAskInteractive(rl, axesToAsk, cfg, (exposure, sofar) => {
8615
+ const v = adopt.exposureShapeVerdict(exposure, adoptShapeCtx(cfg, sofar.tier, extra.trunk, shapeWorkflows, io, extra.branches));
8616
+ return v.ok ? null : v.reason;
8617
+ });
7986
8618
  if (needsStack && opts.stack === undefined) {
7987
8619
  process.stdout.write('\nNo manifest recognised (package.json/composer.json/pyproject.toml/'
7988
8620
  + '.python-version) — the audit requires stack: as a literal key.\n');
@@ -7997,6 +8629,12 @@ async function cmdAdopt(argv) {
7997
8629
  } else {
7998
8630
  const hints = axesToAsk.map(adoptAxisFlagHint).join(' ');
7999
8631
  const stackHint = stackUnresolvable ? ' --stack "<text>"' : '';
8632
+ // #522: the human step goes FIRST — answering exposure none/self is a human's act, so the one
8633
+ // command that finishes the adoption leads, and the explanation follows it.
8634
+ if (axesToAsk.includes('exposure')) {
8635
+ warn('a human finishes this adoption — run at an interactive terminal: colab adopt (or, non-interactively:)');
8636
+ warn(` ${adopt.humanAdoptCommand(adoptAskedFlagPlaceholders(axesToAsk, stackUnresolvable))}`);
8637
+ }
8000
8638
  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
8639
  return 1;
8002
8640
  }
@@ -8021,7 +8659,7 @@ async function cmdAdopt(argv) {
8021
8659
  // written, per "nothing partially written on refusal".
8022
8660
  if (answers.exposure) {
8023
8661
  const proposedExposure = answers.exposure.values.exposure;
8024
- const shapeCtx = adoptShapeCtx(cfg, answers.tier, trunk, workflows, io);
8662
+ const shapeCtx = adoptShapeCtx(cfg, answers.tier, trunk, workflows, io, extra.branches);
8025
8663
  const evidence = consumerEvidence.consumerEvidence(io, workflows);
8026
8664
  const currentExposure = axisAuthority.axisOfRecord(cfg).exposure;
8027
8665
  const verdict = adopt.gateVerdict({
@@ -8035,6 +8673,10 @@ async function cmdAdopt(argv) {
8035
8673
  reason: opts.reason || null,
8036
8674
  });
8037
8675
  if (!verdict.ok) {
8676
+ if (verdict.class === adopt.GATE_CLASS.HUMAN_GATED) {
8677
+ // #522: lead with the one command a human runs, every answer this run had filled in.
8678
+ warn(`a human finishes this adoption — run: ${adopt.humanAdoptCommand(adoptReplayFlags(opts, answers))}`);
8679
+ }
8038
8680
  warn(verdict.message);
8039
8681
  return verdict.exitCode;
8040
8682
  }
@@ -8109,6 +8751,10 @@ async function cmdAdopt(argv) {
8109
8751
  comment: `${adopt.provenanceComment('exposure', m)}${reasonSuffix}`,
8110
8752
  });
8111
8753
  }
8754
+ if (autonomyWrite) {
8755
+ entries.push({ key: 'autonomy', value: opts.autonomy, comment: adopt.provenanceComment('autonomy',
8756
+ { mode: 'flag', flags: ['--autonomy'], date: nowDate, colabHuman, answeredBy: opts.answeredBy || null }) });
8757
+ }
8112
8758
  // Fallback: exposure ends this run still unanswered (declined interactively, or simply not
8113
8759
  // among the axes that got an answer this run) and no `tier` already exists — derive one from
8114
8760
  // (production, deploy), using the EFFECTIVE values (this run's tier answer, if any, else what
@@ -8164,16 +8810,19 @@ async function cmdAdopt(argv) {
8164
8810
  warn('nothing to write — every requested row was already answered, or nothing was supplied to answer it.');
8165
8811
  const verify = opts.noVerify ? null : adoptVerify(repoAbs);
8166
8812
  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; }
8813
+ const land = opts.land ? adoptLand(repoAbs, landTrunk, ['.github/project.yml'], opts.answeredBy) : undefined;
8814
+ const rc = (lf && !lf.ok) || (land && !land.ok) ? 1 : 0;
8815
+ if (opts.json) { print(JSON.stringify({ repo: repoAbs, ...report, verify, written: [], local: lf, land }, null, 2)); return rc; }
8168
8816
  printAdoptReport(report, repoAbs, verify, lf);
8169
- return lf && !lf.ok ? 1 : 0;
8817
+ printAdoptLand(land);
8818
+ return rc;
8170
8819
  }
8171
8820
 
8172
8821
  const newText = adopt.renderDescriptor(rawTextBefore, entries);
8173
8822
  fs.mkdirSync(path.dirname(descriptorFile), { recursive: true });
8174
8823
  fs.writeFileSync(descriptorFile, newText);
8175
8824
 
8176
- const afterExtra = adoptGitExtras(repoAbs);
8825
+ const afterExtra = adoptGitExtras(repoAbs, opts);
8177
8826
  if (local) { afterExtra.trunk = local.trunk; afterExtra.trunkSource = 'local-integration'; }
8178
8827
  const after = adopt.detect(adoptIo(repoAbs), afterExtra);
8179
8828
  // #417: a NEW repo (no descriptor before this run, plain adopt) gets the thin-shell CLAUDE.md
@@ -8182,19 +8831,83 @@ async function cmdAdopt(argv) {
8182
8831
  const shell = local || rawTextBefore !== null ? null : adoptWriteShell(repoAbs, after);
8183
8832
  const verify = opts.noVerify ? null : adoptVerify(repoAbs);
8184
8833
  const lf = local ? adoptLocalFinish(repoAbs, local, opts) : undefined;
8834
+ // #481: --land commits exactly what THIS run wrote — the descriptor, plus the thin shell when
8835
+ // it was written now — never anything else in the working tree.
8836
+ const landPaths = ['.github/project.yml'];
8837
+ if (shell && shell.claude === 'written') landPaths.push(CLAUDE_FILE);
8838
+ if (shell && shell.agents === 'written') landPaths.push('AGENTS.md');
8839
+ const land = opts.land ? adoptLand(repoAbs, landTrunk, landPaths, opts.answeredBy) : undefined;
8840
+ const rc = (lf && !lf.ok) || (land && !land.ok) ? 1 : 0;
8185
8841
  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;
8842
+ print(JSON.stringify({ repo: repoAbs, ...after, verify, written: entries.map((e) => ({ key: e.key, value: e.value })), ...(shell ? { shell } : {}), local: lf, land }, null, 2));
8843
+ return rc;
8188
8844
  }
8189
8845
  for (const e of entries) print(`✓ wrote ${e.key}: ${fmtVal(e.value)}`);
8190
8846
  if (shell) {
8191
- if (shell.claude === 'written') print('✓ wrote CLAUDE.md — the thin shell: @AGENTS.md + the Conventions block (§9 step 5, #417)');
8847
+ 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)');
8848
+ else if (shell.claude === 'written') print('✓ wrote CLAUDE.md — the thin shell: @AGENTS.md + the Conventions block (§9 step 5, #417)');
8192
8849
  else if (shell.claude === 'skipped') print(`· CLAUDE.md not written — ${shell.reason}`);
8193
8850
  if (shell.agents === 'written') print('✓ wrote AGENTS.md — a stub; the repo\'s own instructions go here');
8194
8851
  }
8195
8852
  print('');
8196
8853
  printAdoptReport(after, repoAbs, verify, lf);
8197
- return lf && !lf.ok ? 1 : 0;
8854
+ printAdoptLand(land);
8855
+ return rc;
8856
+ }
8857
+
8858
+ /**
8859
+ * #481 — `--land` preflight: is origin's trunk ahead of this checkout? Landing on a stale trunk
8860
+ * would either fail the push or need a merge, and adopt does neither on a human's behalf. Returns a
8861
+ * refusal message, or null. No origin remote, or no trunk there yet (a first push), is not behind.
8862
+ */
8863
+ function adoptLandBehind(repoAbs, trunk) {
8864
+ if (!git.git(['remote', 'get-url', 'origin'], repoAbs).ok) return null;
8865
+ const f = git.git(['fetch', 'origin', trunk], repoAbs);
8866
+ if (!f.ok) {
8867
+ const remoteHas = git.git(['ls-remote', '--exit-code', '--heads', 'origin', trunk], repoAbs);
8868
+ if (remoteHas.ok) return `--land could not fetch origin/${trunk} — refusing to land on a trunk it cannot see: ${f.stderr || f.stdout}`;
8869
+ return null; // origin has no trunk yet: the landing push creates it
8870
+ }
8871
+ const anc = git.git(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'], repoAbs);
8872
+ if (anc.ok) return null;
8873
+ return `--land refuses: origin/${trunk} has commits this checkout does not — pull ${trunk} first, then re-run`;
8874
+ }
8875
+
8876
+ /**
8877
+ * #481 — commit `paths` (only those) onto trunk and push it. Called only after landVerdict passed
8878
+ * (COLAB_HUMAN=1 + --answered-by, standing on trunk), so the pre-push guard's COLAB_HUMAN door is
8879
+ * the one this push walks through — the same env the human set. Nothing staged for these paths
8880
+ * (already committed) is not an error: it still pushes a trunk that is ahead of origin.
8881
+ */
8882
+ function adoptLand(repoAbs, trunk, paths, answeredBy) {
8883
+ const present = paths.filter((p) => fs.existsSync(path.join(repoAbs, p)));
8884
+ if (!present.length) return { ok: false, trunk, committed: [], sha: null, pushed: false, error: 'no descriptor on disk to land' };
8885
+ const add = git.git(['add', '--', ...present], repoAbs);
8886
+ if (!add.ok) return { ok: false, trunk, committed: [], sha: null, pushed: false, error: `git add failed: ${add.stderr || add.stdout}` };
8887
+ const staged = git.git(['diff', '--cached', '--name-only', '--', ...present], repoAbs);
8888
+ const committed = staged.ok && staged.stdout ? staged.stdout.split('\n').filter(Boolean) : [];
8889
+ if (committed.length) {
8890
+ const c = git.git(['commit', '--only', '-m', adopt.landCommitMessage({ answeredBy, paths: committed }), '--', ...committed], repoAbs);
8891
+ if (!c.ok) return { ok: false, trunk, committed: [], sha: null, pushed: false, error: `git commit failed: ${c.stderr || c.stdout}` };
8892
+ }
8893
+ const head = git.git(['rev-parse', 'HEAD'], repoAbs);
8894
+ const sha = head.ok ? head.stdout : null;
8895
+ if (!git.git(['remote', 'get-url', 'origin'], repoAbs).ok) {
8896
+ return { ok: true, trunk, committed, sha, pushed: false, note: 'no origin remote — committed locally; the first push of trunk carries it' };
8897
+ }
8898
+ const p = git.git(['push', 'origin', `HEAD:refs/heads/${trunk}`], repoAbs);
8899
+ 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}` };
8900
+ return { ok: true, trunk, committed, sha, pushed: true };
8901
+ }
8902
+
8903
+ function printAdoptLand(land) {
8904
+ if (!land) return;
8905
+ print('');
8906
+ if (!land.ok) { print(`✗ land: ${land.error}`); return; }
8907
+ const what = land.committed.length ? `committed ${land.committed.join(', ')} as ${shortSha(land.sha)}` : `nothing new to commit (trunk at ${shortSha(land.sha)})`;
8908
+ print(`✓ land: ${what} on ${land.trunk}${land.pushed ? ` — pushed to origin/${land.trunk}` : ''}`);
8909
+ if (land.note) print(` ${land.note}`);
8910
+ print(' The follow-up branch (CI, guards, docs) is judged by this descriptor — ship it through the normal lane.');
8198
8911
  }
8199
8912
 
8200
8913
  /**
@@ -8224,6 +8937,14 @@ function adoptWriteShell(repoAbs, after) {
8224
8937
  const version = handbookVersion(root);
8225
8938
  const atTag = version === 'v0' ? null : stamp.gitIn(root, ['show', `${version}:templates/repo-CLAUDE-block.md`]);
8226
8939
  const blockText = atTag && atTag.ok && atTag.out ? atTag.out : fs.readFileSync(blockFile, 'utf8');
8940
+ // #449: on a fork, every file adopt creates is one the upstream may add later — a merge conflict
8941
+ // forever after. So no AGENTS.md stub there: with the upstream's own AGENTS.md the shell imports
8942
+ // it, without one CLAUDE.md is the block alone.
8943
+ const forkNoAgents = !!(after && after.fork) && !fs.existsSync(agentsAbs);
8944
+ if (forkNoAgents) {
8945
+ fs.writeFileSync(claudeAbs, adopt.renderClaudeShell(blockText, { version, trunk, tier, importAgents: false }));
8946
+ return { claude: 'written', agents: null, fork: true };
8947
+ }
8227
8948
  fs.writeFileSync(claudeAbs, adopt.renderClaudeShell(blockText, { version, trunk, tier }));
8228
8949
  let agents = 'exists';
8229
8950
  if (!fs.existsSync(agentsAbs)) { fs.writeFileSync(agentsAbs, adopt.renderAgentsStub()); agents = 'written'; }
@@ -9017,6 +9738,19 @@ function newMigrations(mainRoot, trunk, branch) {
9017
9738
  return r.stdout.split('\n').filter(Boolean).filter((f) => migrationPaths.isMigrationPath(f, declared));
9018
9739
  }
9019
9740
 
9741
+ /**
9742
+ * #508 — the content id (migration-grant.js migrationContentId) of `paths` — the branch's migration
9743
+ * files, newMigrations' list — as they stand at `sha`: one `git ls-tree` for their blob ids, a path
9744
+ * the commit no longer has counting as deleted. null when the tree cannot be read or there is
9745
+ * nothing to bind; null never matches a recorded id, so an unreadable tree fails the binding closed.
9746
+ */
9747
+ function migrationContentAt(repoAbs, paths, sha) {
9748
+ if (!sha || !Array.isArray(paths) || paths.length === 0) return null;
9749
+ const r = git.git(['ls-tree', '-z', sha, '--', ...paths], repoAbs);
9750
+ if (!r.ok) return null;
9751
+ return migrationGrant.migrationContentId(migrationGrant.migrationEntriesFromLsTree(r.stdout, paths));
9752
+ }
9753
+
9020
9754
  /**
9021
9755
  * The `no new migrations` row, whole (#98, #401) — the ONE function every ship path calls:
9022
9756
  * `ship --dry`, a real or auto-trunk `ship` (both cmdShip), and `ship --dry --json` (cmdShipDryJson,
@@ -9034,6 +9768,8 @@ function newMigrations(mainRoot, trunk, branch) {
9034
9768
  * evaluateShipSet ctx: the policy (P) from project.yml AT THE TARGET TIP — what the branch merges
9035
9769
  * into, not a working file the branch could have edited; the HEAD — the branch's remote head (what
9036
9770
  * CI ran), which must equal the local ref (what the squash takes), or no reviewer grant can bind;
9771
+ * the migration content id at that HEAD (#508), which a content-bound grant matches instead of
9772
+ * the reviewed HEAD — so the merge-of-trunk sync ship itself demands does not void the grant;
9037
9773
  * and R lazily — every job of every run at that HEAD, read only once some issue clears P+M+HEAD.
9038
9774
  */
9039
9775
  function shipMigrationGate(repoAbs, gh, target, branch, issues) {
@@ -9047,7 +9783,7 @@ function shipMigrationGate(repoAbs, gh, target, branch, issues) {
9047
9783
  } else {
9048
9784
  const records = {};
9049
9785
  for (const n of issues) records[n] = git.ghIssueView(repoAbs, n, ['state', 'labels', 'comments']);
9050
- ctx = shipMigrationCtx(repoAbs, gh, target, branch);
9786
+ ctx = shipMigrationCtx(repoAbs, gh, target, branch, migrations);
9051
9787
  grants = migrationGrant.evaluateShipSet(issues, records, branch, labels.MIGRATION_GRANT_LABEL, ctx);
9052
9788
  }
9053
9789
  return { migrations, ok: grants.ok, ...migDetail(migrations, grants, target, branch, ctx) };
@@ -9055,7 +9791,7 @@ function shipMigrationGate(repoAbs, gh, target, branch, issues) {
9055
9791
 
9056
9792
  /** P, HEAD and the R thunk for shipMigrationGate. The thunk memoises its one verdict on the ctx
9057
9793
  * (`roundtripResult`) so the payload can report what R saw without a second read. */
9058
- function shipMigrationCtx(repoAbs, gh, target, branch) {
9794
+ function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
9059
9795
  const policy = migrationGrant.parseGrantPolicy(projectDocAt(repoAbs, target)).policy;
9060
9796
  const remote = git.remoteInfo(repoAbs).name || 'origin';
9061
9797
  const ls = git.git(['ls-remote', remote, `refs/heads/${branch}`], repoAbs);
@@ -9067,7 +9803,9 @@ function shipMigrationCtx(repoAbs, gh, target, branch) {
9067
9803
  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
9804
  else headSha = remoteSha;
9069
9805
  const trust = trustAt(repoAbs, target);
9070
- const ctx = { policy, headSha, headNote, roundtripResult: null, trust,
9806
+ // #508: what the branch's migration files ARE at the shipped head, for a content-bound grant.
9807
+ const contentId = headSha ? migrationContentAt(repoAbs, migrations, headSha) : null;
9808
+ const ctx = { policy, headSha, contentId, headNote, roundtripResult: null, trust,
9071
9809
  labelActors: (n) => git.ghIssueLabelActors(repoAbs, n, labels.MIGRATION_GRANT_LABEL) };
9072
9810
  ctx.roundtrip = () => {
9073
9811
  const d = git.git(['diff', '--name-only', `${target}...${branch}`], repoAbs);
@@ -9101,16 +9839,17 @@ function migDetail(migrations, grants, target, branch, ctx) {
9101
9839
  branch, files: [...migrations],
9102
9840
  policy: ctx ? ctx.policy : null,
9103
9841
  headSha: ctx ? ctx.headSha : null,
9842
+ contentId: ctx ? ctx.contentId || null : null,
9104
9843
  // #407: the human list as read from the TARGET — null when undeclared (association class).
9105
9844
  trustHumans: ctx && ctx.trust && ctx.trust.declared ? [...ctx.trust.humans] : null,
9106
9845
  roundtrip: ctx && ctx.roundtripResult ? { ok: ctx.roundtripResult.ok, reason: ctx.roundtripResult.reason } : null,
9107
9846
  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 } : {}) })),
9847
+ ...(g.role === 'reviewer' ? { reviewer: g.reviewer, head: g.head, via: g.via || 'head', migrations: g.migrations || null } : {}) })),
9109
9848
  missing: grants.missing.map((m) => ({ issue: m.issue, failed: m.failed || null,
9110
9849
  reason: m.failed === 'head' && ctx && ctx.headNote ? `${m.reason} (${ctx.headNote})` : m.reason })),
9111
9850
  };
9112
9851
  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(' ');
9852
+ 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
9853
  const roles = [...new Set(grants.granted.map((g) => g.role || 'human'))].join('+');
9115
9854
  return { text: `${migrations.length} present, exempted by a ${roles} grant on ${by} for branch "${branch}" — ${files}`, payload };
9116
9855
  }
@@ -9206,7 +9945,11 @@ function ciGrantTrailerLine(grantVerdict, branch, trunk) {
9206
9945
  if (!grantVerdict || !grantVerdict.ok || !grantVerdict.granted.length) return null;
9207
9946
  const g = grantVerdict.granted[0]; // redSha/evidenceSha are identical across the whole granted set (evaluateShipSet)
9208
9947
  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)}`;
9948
+ // #504: a reviewer grant appends who reviewed it; the `over-red <trunk>@<sha>` part the anti-stacking
9949
+ // scan (ci-cure.js priorRedShaFromMessage) reads is unchanged.
9950
+ const rv = grantVerdict.granted.filter((x) => x.role && x.role !== 'human');
9951
+ const via = rv.length ? ` via ${rv[0].role} ${[...new Set(rv.map((x) => x.reviewer))].join(',')}` : '';
9952
+ return `CI-Grant: ${issues} branch ${branch} over-red ${trunk}@${shortSha(g.redSha)} evidence ${shortSha(g.evidenceSha)}${via}`;
9210
9953
  }
9211
9954
 
9212
9955
  /**
@@ -9221,17 +9964,26 @@ function ciGrantTrailerLine(grantVerdict, branch, trunk) {
9221
9964
  * line without touching the scan.
9222
9965
  *
9223
9966
  * 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
9967
+ * That suffix is not decoration: anti-stacking permits ONE exemption per continuous red (more only on progress, #477)
9225
9968
  * episode, so a later reader has to be able to tell WHICH door spent it — and a cure that went
9226
9969
  * through the widened door on a branch editing the CI config is a materially different fact from an
9227
9970
  * ordinary one. The commit is the only artifact that still says so after the runs age out.
9228
9971
  */
9229
9972
  function ciCureTrailerLine(cureVerdict, branch, trunk) {
9230
9973
  if (!cureVerdict || !cureVerdict.ok) return null;
9231
- const via = cureVerdict.carveOut
9974
+ const via = (cureVerdict.carveOut
9232
9975
  ? ` 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}`;
9976
+ : '') + (cureVerdict.dryRun ? ` via dry-run jobs ${cureVerdict.dryRun.jobs.join(',')}` : '')
9977
+ + (cureVerdict.dispatch ? ` via dispatch jobs ${cureVerdict.dispatch.jobs.join(',')}` : ''); // #510
9978
+ // #475/#476: a cure that changed a manifest under an admission says which, for the same reason.
9979
+ const adm = cureVerdict.admitted || {};
9980
+ const manifest = [adm.scripts ? 'add-only-scripts' : null, adm.pins ? 'pin-only-requirements' : null].filter(Boolean);
9981
+ const admittedSuffix = manifest.length ? ` admitted ${manifest.join(',')}` : '';
9982
+ // #477: a cure that spent condition 3 by progress past a prior exemption says so, and which jobs
9983
+ // healed — the next cure on this red compares against THIS line's over-red sha.
9984
+ const progressSuffix = cureVerdict.progress
9985
+ ? ` after-progress healed ${cureVerdict.progress.healed.join(',')}` : '';
9986
+ return `CI-Cure: branch ${branch} over-red ${trunk}@${shortSha(cureVerdict.redSha)} evidence ${shortSha(cureVerdict.evidenceSha)}${via}${admittedSuffix}${progressSuffix}`;
9235
9987
  }
9236
9988
 
9237
9989
  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]
@@ -9362,7 +10114,9 @@ makes today); (2) the branch's own CI is green AT ITS OWN CURRENT HEAD, measured
9362
10114
  and (2b, #297) every job RED on trunk at the red sha exists in the branch's runs at that head,
9363
10115
  completed and \`success\` (a green run in which the failing check never ran proves nothing);
9364
10116
  (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
10117
+ stayed continuously red since) — UNLESS trunk's red-job set now is a STRICT subset of the set at the
10118
+ red sha the prior exemption's trailer names (#477: progress, so two failures healed by two fixes need
10119
+ no human; an unchanged or grown set still refuses); (4) the branch diff does not touch \`.github/workflows/**\` (a branch
9366
10120
  may not self-certify a change to the CI configuration grading it; renames count) — UNLESS it passes
9367
10121
  the #321 CARVE-OUT below; (5, #297) the branch diff does not change the \`scripts\` block of any
9368
10122
  \`package.json\` — CI templates read that block to decide which checks run, so it is part of the
@@ -9383,7 +10137,7 @@ nothing — this is the sub-test that catches a fast exit, because GitHub report
9383
10137
  were all skipped as \`conclusion: success\`); (4c) each of those jobs cost at least the wall time its
9384
10138
  failure did on trunk. Anything unmeasurable refuses, exactly as before. A carve-out cure names the
9385
10139
  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.
10140
+ 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
10141
  Its own honest limit: it proves the red jobs still ran the steps they ran and still cost the time —
9388
10142
  never what those steps ASSERTED. Known false refusal: a trunk job that failed by TIMEOUT ran longer
9389
10143
  than any healthy run, so (4c) refuses the genuine repair; take the ordinary ci-grant door there.
@@ -9464,7 +10218,9 @@ It never waits: each call reads the remote, takes ONE step and exits —
9464
10218
  trunk CI red (the cure/grant doors apply per member, never to a batch), fewer than two members
9465
10219
  can join, or the combined run is red — classify it: red:infra → the printed \`gh run rerun\`,
9466
10220
  once; red:finding, or red again after that one re-run → serial
9467
- 1 refused (a broken checkout, an unreadable remote)
10221
+ 1 refused (a broken checkout, an unreadable remote) — or the land push was refused while trunk did
10222
+ NOT move (a local pre-push hook, a remote rejection): the push's own output is echoed, and
10223
+ re-running hits the same refusal until its cause is fixed (#509)
9468
10224
  One batch per base: a batch at this base carrying OTHER members is waited on (exit 3) while its run
9469
10225
  is pending or green, but a declined one — its combined run red — is deleted and the batch you asked
9470
10226
  for is built in its place, so the survivors of a decline can batch without landing serially first (#391).
@@ -9512,7 +10268,9 @@ Options:
9512
10268
  warning). --dry prints "Machine trailer: …" saying which way it will go.
9513
10269
  --refs <N[,M]> reference these claimed issues (Refs #N) instead of closing them — for a
9514
10270
  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
10271
+ Comma-separated, and repeatable: --refs A --refs B is --refs A,B (#479 —
10272
+ every other value flag to ship refuses a repeat). Each must be a claimed
10273
+ issue on the branch. An issue carrying
9516
10274
  the "tracking" label is treated this way automatically, no flag needed. The
9517
10275
  claim is still released either way — only Closes→Refs changes.
9518
10276
  #385: a --refs'd issue whose body still has an unticked "- [ ]" box (under
@@ -9555,7 +10313,8 @@ Options:
9555
10313
  instead — an unattended caller must NOT read it as a no-op. "pr-pending"
9556
10314
  (#350) means a real run would open/reuse a PR and PAUSE (exit 3) — additive
9557
10315
  keys \`coreReview\` ({ active, verdict, inertReason, codeownersPath, corePaths,
9558
- headSha, pr, approval }) and \`machineTrailer\` ("Machine: <label>") say why.
10316
+ ignoredOwners (#483: a fork's inherited foreign-org teams), headSha, pr,
10317
+ approval }) and \`machineTrailer\` ("Machine: <label>") say why.
9559
10318
  \`machineTrailer\` is null whenever the trailer is omitted (#367), and
9560
10319
  \`machineTrailerDecision\` ({ include, reason, visibility, room, failClosed },
9561
10320
  null on evidence-close) says which way the squash will go and why.
@@ -9905,23 +10664,91 @@ function descriptorHolds(doc) {
9905
10664
  * caller can build the --dry --json `ciGrant`/`ciCure` payloads from the SAME verdicts the prose
9906
10665
  * detail string was built from — see ciGrantPayload/ciCurePayload, below.
9907
10666
  */
9908
- function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
10667
+ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk, branch = null) {
9909
10668
  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);
10669
+ const r = readCiVerdict(repoAbs, gh, target, trunk);
10670
+ const nw = noWorkflowTrunkDoor(repoAbs, r, target, trunk, branch);
10671
+ if (nw) return { name, ...nw, grantVerdict: null, cureVerdict: null };
10672
+ if (r.final) return { name, ...r.verdict, grantVerdict: null, cureVerdict: null };
10673
+ return applyRedTrunkExemptions({ name, ...r.verdict }, target, trunk, r.run.sha, grantThunk, cureThunk);
10674
+ }
10675
+
10676
+ /**
10677
+ * #482: a trunk with NO repo-owned workflow file at its head sha (a freshly adopted repo whose
10678
+ * adoption branch is what adds CI) can never draw a run, so its `none` is not a gap in CI — there is
10679
+ * no CI there to be red. It reads `none` and gets Branch CI's `none`-that-cannot-arrive treatment
10680
+ * (CONVENTIONS.md §4): the candidate's OWN run at its remote head decides. Green there → the row
10681
+ * passes; anything else → the ordinary refusal stands, with the reason appended.
10682
+ *
10683
+ * Fails closed: only a trunk sha present locally whose tree demonstrably has no
10684
+ * `.github/workflows/*.yml|yaml` qualifies. A trunk that HAS workflows but no run at its sha is a
10685
+ * real gap (CI not wired, or never started) and still blocks exactly as before. Runs ahead of the
10686
+ * #413 grace window too: a run that can never exist is not worth waiting ten minutes for. Returns null when
10687
+ * the door does not apply, or a `{ok, class, detail}` verdict when it does.
10688
+ */
10689
+ function noWorkflowTrunkDoor(repoAbs, r, target, trunk, branch) {
10690
+ if (target !== trunk || !branch || !r.run || r.run.status !== 'none' || !r.run.sha || r.verdict.ok) return null;
10691
+ if (trunkWorkflowFiles(repoAbs, r.run.sha) !== 0) return null;
10692
+ const at = `${trunk}@${shortSha(r.run.sha)}`;
10693
+ const own = git.ghRunForSha(repoAbs, branch);
10694
+ // Branch not on the remote, or its runs unreadable: nothing to decide with — the prior verdict stands.
10695
+ if (!own) return null;
10696
+ const ownAt = own.sha ? `${branch}@${shortSha(own.sha)}` : branch;
10697
+ if (own && own.status === 'completed' && own.conclusion === 'success') {
10698
+ const n = own.runCount == null ? 1 : own.runCount;
10699
+ return { ok: true, class: null,
10700
+ 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)}` };
10701
+ }
10702
+ const why = own.status === 'none' ? 'has no run' : `is status=${own.status} conclusion=${own.conclusion || 'none'}`;
10703
+ return { ok: false, class: own.status !== 'completed' && own.status !== 'none' ? SELF_CLEARING : HUMAN_GATED,
10704
+ detail: `none — ${at} has no repo-owned workflow (#482), so the branch's own run decides, and ${ownAt} ${why}${excludedRunsNote(r.run)}` };
10705
+ }
10706
+
10707
+ /** Number of workflow files in `.github/workflows` at `sha`, or null when the tree cannot be read. */
10708
+ function trunkWorkflowFiles(repoAbs, sha) {
10709
+ if (!git.git(['cat-file', '-e', `${sha}^{commit}`], repoAbs).ok) return null;
10710
+ const ls = git.git(['ls-tree', '--name-only', `${sha}:.github/workflows`], repoAbs);
10711
+ if (!ls.ok) {
10712
+ // No such directory is a real zero; any other failure is unknown (fail closed).
10713
+ const dir = git.git(['ls-tree', '--name-only', sha, '.github/workflows'], repoAbs);
10714
+ return dir.ok && dir.stdout.trim() === '' ? 0 : null;
10715
+ }
10716
+ return ls.stdout.split('\n').map((x) => x.trim()).filter((f) => /\.ya?ml$/.test(f)).length;
10717
+ }
10718
+
10719
+ /**
10720
+ * The CI read and its classification, BEFORE any exemption door (#463) — the one function both
10721
+ * `shipCiCheck` above and `colab trunk-ci` (cmdTrunkCi) call, so code-triage's "is trunk red?" and
10722
+ * ship's "trunk CI green" precondition can no longer disagree about a sha. They did: triage read
10723
+ * "red only when every run completed and none succeeded" in its own `gh run list` filter, so a sha
10724
+ * with one green workflow beside a red one read GREEN to triage while ship parked every candidate.
10725
+ *
10726
+ * Returns `{ run, verdict, final }`. `verdict` is `{ok, class, detail}`; `run` is the summarized
10727
+ * run (null when gh is unusable or the read failed). `final` is true when no exemption door applies
10728
+ * (green, self-clearing, unreadable, or a batch substitute answered) — the caller returns `verdict`
10729
+ * as is; false means a HUMAN_GATED verdict that `shipCiCheck` still offers to the cure rule and the
10730
+ * ci-grant. `trunk-ci` deliberately reports the pre-exemption verdict: an exemption lets ONE
10731
+ * branch past a red trunk, it does not make the trunk green, and the red still needs an owner.
10732
+ */
10733
+ function readCiVerdict(repoAbs, gh, target, trunk) {
10734
+ if (!gh) return { run: null, final: true, verdict: { ok: false, class: SELF_CLEARING, detail: `gh not usable (${ghUnusableWhy(repoAbs)}) — cannot confirm CI` } };
10735
+ // #503: only runs that VERIFY the code count — a post-CI release/deploy run at the same sha is set
10736
+ // aside and named, never a red and never a reason to wait (tools/lib/verify-runs.js).
10737
+ const readOpts = { verifying: verifyRuns.parsePolicy(projectDoc(repoAbs)) };
10738
+ let run = git.ghRunForSha(repoAbs, target, undefined, undefined, readOpts);
9912
10739
  let via = target;
9913
10740
  if (run && run.status === 'none' && target !== trunk) {
9914
- run = git.ghRunForSha(repoAbs, trunk);
10741
+ run = git.ghRunForSha(repoAbs, trunk, undefined, undefined, readOpts);
9915
10742
  via = `${trunk} (line "${target}" has no runs — ungated, advisory)`;
9916
10743
  }
9917
- if (!run) return { name, ok: false, class: SELF_CLEARING, detail: 'gh run list failed', grantVerdict: null, cureVerdict: null };
10744
+ if (!run) return { run: null, final: true, verdict: { ok: false, class: SELF_CLEARING, detail: 'gh run list failed' } };
9918
10745
  // #413: an empty BRANCH-filtered read of trunk's head is a second opinion away from `none`. It was
9919
10746
  // measured coming back empty for a trunk sha whose green run existed, then clearing a minute later
9920
10747
  // — and `none` classes HUMAN_GATED, so a transient read parked a ready candidate for a human.
9921
10748
  // Re-read the same sha by commit (the read `release finalize` already trusts, #339) before
9922
10749
  // believing it. A failed re-read changes nothing: the branch read's `none` stands.
9923
10750
  if (run.status === 'none' && target === trunk) {
9924
- const byCommit = git.ghRunForCommitAnyRef(repoAbs, run.sha);
10751
+ const byCommit = git.ghRunForCommitAnyRef(repoAbs, run.sha, undefined, readOpts);
9925
10752
  if (byCommit && byCommit.status !== 'none') {
9926
10753
  run = byCommit;
9927
10754
  via = `${trunk} (by commit — the branch-filtered read was empty)`;
@@ -9936,7 +10763,7 @@ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
9936
10763
  const fresh = ciVerdict.emptyReadVerdict(git.commitTimeMs(repoAbs, run.sha));
9937
10764
  if (fresh.fresh) {
9938
10765
  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` };
10766
+ 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
10767
  }
9941
10768
  }
9942
10769
  // #373: trunk's own run not there yet or still in flight (never a finished red) — a batch that landed
@@ -9944,10 +10771,43 @@ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
9944
10771
  // Inert (no gh call) unless project.yml declares ship-batch > 1.
9945
10772
  if (!verdict.ok && target === trunk && (run.status === 'none' || verdict.class === SELF_CLEARING)) {
9946
10773
  const sub = shipBatchTrunkSubstitute(repoAbs, trunk, run.sha);
9947
- if (sub) return { name, ...sub, grantVerdict: null, cureVerdict: null };
10774
+ if (sub) return { run, final: true, verdict: sub };
9948
10775
  }
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);
10776
+ if (verdict.ok && target === trunk) verdict = treeGreenVerdict(repoAbs, run, verdict);
10777
+ return { run, verdict, final: verdict.ok || verdict.class !== HUMAN_GATED };
10778
+ }
10779
+
10780
+ /**
10781
+ * #493: a green trunk read whose suite was SKIPPED because the CI guard found a green run of the
10782
+ * same workflow at an identical tree — name the run it relied on. The run's `success` is already
10783
+ * the verdict (same as #418's sha skip); the citation is the audit pointer, so a citation that
10784
+ * cannot be read leaves the verdict green and says so. One thing turns it red: the cited head is
10785
+ * local and its tree provably differs from trunk's — the skip relied on a run of a DIFFERENT
10786
+ * tree, so trunk is untested (HUMAN_GATED, a person looks). An ordinary green run costs one
10787
+ * check-runs read and keeps its detail byte-identical.
10788
+ */
10789
+ function treeGreenVerdict(repoAbs, run, verdict) {
10790
+ const checks = git.ghCommitCheckRuns(repoAbs, run.sha);
10791
+ const ids = treeGreen.treeSkipCheckRuns(checks);
10792
+ if (!ids || !ids.length) return verdict;
10793
+ const cites = [];
10794
+ let unreadable = 0;
10795
+ const treeOf = (sha) => {
10796
+ const r = git.git(['rev-parse', '--verify', '--quiet', `${sha}^{tree}`], repoAbs);
10797
+ return r.ok ? r.stdout.trim() : null;
10798
+ };
10799
+ const ours = treeOf(run.sha);
10800
+ for (const id of ids) {
10801
+ const cite = treeGreen.parseCitation(git.ghCheckRunAnnotations(repoAbs, id));
10802
+ if (!cite) { unreadable++; continue; }
10803
+ const theirs = treeOf(cite.head);
10804
+ if (ours && theirs && ours !== theirs) {
10805
+ return { ok: false, class: HUMAN_GATED,
10806
+ 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` };
10807
+ }
10808
+ cites.push({ ...cite, proof: ours && theirs ? 'verified' : 'unverified' });
10809
+ }
10810
+ return { ...verdict, detail: verdict.detail + treeGreen.citationNote(cites, unreadable), treeGreen: cites.map((c) => c.url) };
9951
10811
  }
9952
10812
 
9953
10813
  /**
@@ -9973,6 +10833,35 @@ function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk) {
9973
10833
  * the detail string still reads sensibly rather than "undefined runs".
9974
10834
  */
9975
10835
  function classifyCiRun(repoAbs, run, at) {
10836
+ const v = classifyCiRunRaw(repoAbs, run, at);
10837
+ return { ...v, detail: v.detail + excludedRunsNote(run) + supersededRunsNote(run) + verifyRuns.setAsideNote(run && run.setAside) };
10838
+ }
10839
+
10840
+ /**
10841
+ * #461: earlier runs of the same workflow at this sha that a newer run of it superseded — set aside
10842
+ * by git.summarizeRunsForCommit before the verdict, and named here so the reader sees what the
10843
+ * verdict did not judge. '' when none.
10844
+ */
10845
+ function supersededRunsNote(run) {
10846
+ const sup = run && Array.isArray(run.superseded) ? run.superseded : [];
10847
+ if (!sup.length) return '';
10848
+ const names = sup.map((x) => `${x.workflowName || 'unnamed'} (${x.conclusion || x.status || '?'}${x.databaseId ? `, run ${x.databaseId}` : ''})`);
10849
+ return ` — set aside ${sup.length} superseded run${sup.length === 1 ? '' : 's'} (a newer run of the same workflow decides, #461): ${names.join(', ')}`;
10850
+ }
10851
+
10852
+ /**
10853
+ * #451: the runs a verdict did NOT count, named in its detail — runs from workflows the repo does
10854
+ * not own (`event: dynamic`, e.g. Dependabot Updates) are dropped by git.summarizeRunsForCommit
10855
+ * before the verdict is computed, and a reader must be able to see what was dropped. '' when none.
10856
+ */
10857
+ function excludedRunsNote(run) {
10858
+ const ex = run && Array.isArray(run.excluded) ? run.excluded : [];
10859
+ if (!ex.length) return '';
10860
+ const names = ex.map((x) => `${x.workflowName || 'unnamed'} (${x.conclusion || x.status || '?'}${x.databaseId ? `, run ${x.databaseId}` : ''})`);
10861
+ return ` — excluded ${ex.length} run${ex.length === 1 ? '' : 's'} from workflows this repo does not own (event: dynamic, #451): ${names.join(', ')}`;
10862
+ }
10863
+
10864
+ function classifyCiRunRaw(repoAbs, run, at) {
9976
10865
  if (run.status === 'completed') {
9977
10866
  if (run.conclusion === 'success') {
9978
10867
  const n = run.runCount == null ? 1 : run.runCount;
@@ -10156,9 +11045,10 @@ function applyRedTrunkExemptions(raw, target, trunk, redSha, grantThunk, cureThu
10156
11045
  const via = cureVerdict.carveOut
10157
11046
  ? ` 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
11047
  : '';
11048
+ const viaDry = cureVerdict.dryRun ? ` — main-only job(s) ${cureVerdict.dryRun.jobs.join(', ')} proven by a DRY RUN on the branch (#474)` : '';
10159
11049
  return {
10160
11050
  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})`,
11051
+ 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})`,
10162
11052
  grantVerdict: null, cureVerdict,
10163
11053
  };
10164
11054
  }
@@ -10166,9 +11056,14 @@ function applyRedTrunkExemptions(raw, target, trunk, redSha, grantThunk, cureThu
10166
11056
  const grantVerdict = grantThunk ? grantThunk(redSha) : null;
10167
11057
  if (grantVerdict && grantVerdict.ok) {
10168
11058
  const by = grantVerdict.granted.map((g) => '#' + g.issue).join(' ');
11059
+ // #504: a reviewer grant says so — it must never render as a human's decision.
11060
+ const rv = grantVerdict.granted.filter((g) => g.role && g.role !== 'human');
11061
+ const who = rv.length
11062
+ ? `a ${rv[0].role} ci-grant (reviewer ${[...new Set(rv.map((g) => g.reviewer))].join(', ')}, cures ${[...new Set(rv.flatMap((g) => g.cures || []))].join('; ')})`
11063
+ : 'a human ci-grant';
10169
11064
  return {
10170
11065
  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})`,
11066
+ detail: `PRECONDITION OVERRIDDEN by ${who} on ${by} — trunk was red at ${shortSha(redSha)} (raw: ${raw.detail})`,
10172
11067
  grantVerdict, cureVerdict,
10173
11068
  };
10174
11069
  }
@@ -10191,12 +11086,21 @@ function shipCiGrants(repoAbs, gh, issues, branch, trunk, redSha) {
10191
11086
  missing: [{ issue: null, reason: `gh not usable (${ghUnusableWhy(repoAbs)}) — a CI grant lives on the tracker and cannot be confirmed` }] };
10192
11087
  }
10193
11088
  const records = {};
10194
- for (const n of issues) records[n] = git.ghIssueView(repoAbs, n, ['state', 'labels', 'comments']);
11089
+ // `title` (#504): a reviewer grant requires its issue to be titled `TRUNK RED:`.
11090
+ for (const n of issues) records[n] = git.ghIssueView(repoAbs, n, ['state', 'labels', 'comments', 'title']);
10195
11091
  const evRun = git.ghRunForSha(repoAbs, branch);
10196
11092
  const evidence = !evRun ? null : { ok: evRun.status === 'completed' && evRun.conclusion === 'success', sha: evRun.sha };
10197
11093
  return ciGrant.evaluateShipSet(issues, records, branch, trunk, redSha, evidence, labels.CI_GRANT_LABEL, {
10198
11094
  trust: trustAt(repoAbs, trunk),
10199
11095
  labelActors: (n) => git.ghIssueLabelActors(repoAbs, n, labels.CI_GRANT_LABEL),
11096
+ // #504 — the reviewer role: the opt-in as committed on TRUNK (never the branch), the clock for a
11097
+ // host's revoke window, and trunk's red checks at redSha, read lazily and at most once.
11098
+ policy: ciGrant.parseGrantPolicy(projectDocAt(repoAbs, trunk)).policy,
11099
+ now: Date.now(),
11100
+ redJobs: () => {
11101
+ const jobs = trunkRedRunJobs(repoAbs, trunk, redSha);
11102
+ return jobs === null ? null : ciCure.redJobSet(jobs);
11103
+ },
10200
11104
  });
10201
11105
  }
10202
11106
 
@@ -10211,7 +11115,8 @@ function ciGrantPayload(ciResult) {
10211
11115
  const g = ciResult.grantVerdict;
10212
11116
  return {
10213
11117
  ok: g.ok,
10214
- granted: g.granted.map((x) => ({ issue: x.issue, by: x.by, at: x.at, redSha: x.redSha, evidenceSha: x.evidenceSha })),
11118
+ granted: g.granted.map((x) => ({ issue: x.issue, by: x.by, at: x.at, redSha: x.redSha, evidenceSha: x.evidenceSha,
11119
+ ...(x.role ? { role: x.role, reviewer: x.reviewer, head: x.head, cures: x.cures } : {}) })),
10215
11120
  missing: g.missing.map((m) => ({ issue: m.issue, reason: m.reason })),
10216
11121
  };
10217
11122
  }
@@ -10278,11 +11183,38 @@ function shipCiCure(repoAbs, gh, target, trunk, redSha, branch) {
10278
11183
  // so a branch that cannot cure pays no job-level `gh` calls for it.
10279
11184
  const jobEvidence = (containsRedSha && evidence && evidence.ok)
10280
11185
  ? shipCureJobEvidence(repoAbs, trunk, redSha, branch, evRun) : null;
10281
- const verdict = ciCure.cureVerdict({ containsRedSha, evidence, redSha, stacking, jobEvidence,
11186
+ // #474: which workflows at the branch head offer a dry run — a static read (git show), read only
11187
+ // when job evidence exists, so a branch that already refuses on containment or 2a pays nothing.
11188
+ const capable = jobEvidence && evidence ? dryRunCapableWorkflows(repoAbs, evidence.sha) : [];
11189
+ // #510: which branch workflows a plain workflow_dispatch can run — same static read, same gating.
11190
+ const dispatchable = jobEvidence && evidence ? dispatchableWorkflows(repoAbs, evidence.sha) : [];
11191
+ // #477: a stacked refusal may be lifted by progress — measure the prior red set only then.
11192
+ const priorRedJobs = jobEvidence && stacking && stacking.stacked ? priorExemptionRedJobs(repoAbs, trunk, stacking) : null;
11193
+ const verdict = ciCure.cureVerdict({ containsRedSha, evidence, redSha, stacking, jobEvidence, priorRedJobs,
10282
11194
  workflowsTouched: diff.workflowsTouched,
10283
11195
  manifestScriptsTouched: diff.manifestScriptsTouched, manifestPaths: diff.manifestPaths,
10284
- pythonManifestTouched: diff.pythonManifestTouched, pythonManifestPaths: diff.pythonManifestPaths });
10285
- return { ...verdict, redSha, evidenceSha: evidence ? evidence.sha : null };
11196
+ manifestScriptsAddOnly: diff.manifestScriptsAddOnly,
11197
+ pythonManifestTouched: diff.pythonManifestTouched, pythonManifestPaths: diff.pythonManifestPaths,
11198
+ pythonPinOnly: diff.pythonPinOnly,
11199
+ dryRunCapable: capable.map((w) => w.name),
11200
+ dispatchable: dispatchable.map((w) => w.name), branchRuns: jobEvidence ? jobEvidence.branchRuns : null });
11201
+ // The dispatch plan carries the FILE and the exact command, so the refusal can name it and the
11202
+ // real ship path can run it — measurement only here; nothing is dispatched by this function.
11203
+ const dryRunDispatch = verdict.dryRunWanted
11204
+ ? verdict.dryRunWanted.map((name) => {
11205
+ const w = capable.find((c) => c.name === name);
11206
+ return { workflow: name, file: w.file, command: `gh workflow run ${w.file} --ref ${branch} -f ${DRY_RUN_INPUT}=true` };
11207
+ })
11208
+ : null;
11209
+ // #510: same shape for a plain workflow_dispatch of a branch workflow whose red job a push skipped.
11210
+ const dispatchCure = verdict.dispatchWanted
11211
+ ? verdict.dispatchWanted.map((name) => {
11212
+ const w = dispatchable.find((c) => c.name === name);
11213
+ return { workflow: name, file: w.file, command: `gh workflow run ${w.file} --ref ${branch}` };
11214
+ })
11215
+ : null;
11216
+ return { ...verdict, ...(dryRunDispatch ? { dryRunDispatch } : {}), ...(dispatchCure ? { dispatchCure } : {}),
11217
+ redSha, evidenceSha: evidence ? evidence.sha : null };
10286
11218
  }
10287
11219
 
10288
11220
  /**
@@ -10304,34 +11236,69 @@ function shipCiCure(repoAbs, gh, target, trunk, redSha, branch) {
10304
11236
  function shipCureJobEvidence(repoAbs, trunk, redSha, branch, evRun) {
10305
11237
  if (!evRun || !evRun.sha) return null;
10306
11238
 
10307
- // ALL runs at the red sha, not the single row `ghRunForCommit` would pick: a red job can sit in a
11239
+ const redRunJobs = trunkRedRunJobs(repoAbs, trunk, redSha);
11240
+ if (redRunJobs === null) return null;
11241
+
11242
+ const branchRuns = git.ghRunsForCommit(repoAbs, branch, evRun.sha);
11243
+ if (branchRuns === null || branchRuns.length === 0) return null;
11244
+ const branchRunJobs = [];
11245
+ for (const r of branchRuns) {
11246
+ const jobs = git.ghRunJobs(repoAbs, r.databaseId);
11247
+ if (jobs === null) return null;
11248
+ // #510: workflowId, event and headSha too — the dispatch rules (W1/W2) read them per job.
11249
+ branchRunJobs.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '', workflowId: r.workflowId ?? null,
11250
+ event: r.event || null, headSha: r.headSha || null })));
11251
+ }
11252
+
11253
+ const shaped = ciCure.shapeJobEvidence({ redRunJobs, branchRunJobs, branchSha: evRun.sha });
11254
+ // #510: the run-level rows too, for the dispatch plan's gates (d) and (e).
11255
+ return shaped && { ...shaped, branchRuns: branchRuns.map((r) => ({ workflowName: r.workflowName || '', workflowId: r.workflowId ?? null,
11256
+ event: r.event || null, status: r.status, conclusion: r.conclusion || null })) };
11257
+ }
11258
+
11259
+ /**
11260
+ * Every job of every not-green, repo-owned run on `trunk` at `sha`, each tagged with its run's
11261
+ * `workflowName` — the raw input of ci-cure.js's `shapeJobEvidence`/`redJobSet`. `null` on any failed
11262
+ * read, or when no not-green run exists there (nothing red to name). `limit` widens the run window
11263
+ * for an OLDER sha (#477's prior red sha), which a 10-row list of trunk's latest runs may not reach.
11264
+ */
11265
+ function trunkRedRunJobs(repoAbs, trunk, sha, limit) {
11266
+ // ALL runs at the sha, not the single row `ghRunForCommit` would pick: a red job can sit in a
10308
11267
  // sibling workflow the picker never returned, and admitting a carve-out while that job is still
10309
11268
  // 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;
11269
+ // #451: a run from a workflow the repo does not own is not part of trunk's red — same drop the
11270
+ // verdict itself makes (git.summarizeRunsForCommit), so cure evidence never chases its jobs.
11271
+ const runsAll = git.ghRunsForCommit(repoAbs, trunk, sha, limit);
11272
+ const runs = runsAll === null ? null : runsAll.filter(git.isRepoOwnedRun);
11273
+ if (runs === null || runs.length === 0) return null;
10312
11274
 
10313
11275
  // Same inverted allowlist git.js uses at run level (#146/#165): only `success`/`cancelled` are
10314
11276
  // 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');
11277
+ const notGreen = runs.filter((r) => r.status === 'completed' && r.conclusion !== 'success' && r.conclusion !== 'cancelled');
10316
11278
  if (notGreen.length === 0) return null;
10317
11279
 
10318
- const redRunJobs = [];
11280
+ const out = [];
10319
11281
  for (const r of notGreen) {
10320
11282
  const jobs = git.ghRunJobs(repoAbs, r.databaseId);
10321
11283
  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 || '' })));
11284
+ out.push(...jobs.map((j) => ({ ...j, workflowName: r.workflowName || '', workflowId: r.workflowId ?? null })));
10332
11285
  }
11286
+ return out;
11287
+ }
10333
11288
 
10334
- return ciCure.shapeJobEvidence({ redRunJobs, branchRunJobs });
11289
+ /**
11290
+ * The red-job set at the red sha the prior exemption on this continuous red was measured against
11291
+ * (#477) — read only when condition 3 refused as stacked AND job evidence exists (containment + 2a
11292
+ * passed), so no other ship pays for it. The trailer's sha is usually short; it is resolved to a full
11293
+ * sha first. `null` (unmeasured → no progress → the stacked refusal stands) on any failed step.
11294
+ */
11295
+ function priorExemptionRedJobs(repoAbs, trunk, stacking) {
11296
+ const short = stacking && stacking.stacked && stacking.prior ? stacking.prior.redSha : null;
11297
+ if (!short) return null;
11298
+ const full = git.git(['rev-parse', '--verify', '--quiet', `${short}^{commit}`], repoAbs);
11299
+ if (!full.ok || !full.stdout.trim()) return null;
11300
+ const raw = trunkRedRunJobs(repoAbs, trunk, full.stdout.trim(), 100);
11301
+ return raw === null ? null : ciCure.redJobSet(raw);
10335
11302
  }
10336
11303
 
10337
11304
  /**
@@ -10357,9 +11324,132 @@ function ciCurePayload(ciResult) {
10357
11324
  carveOut: c.carveOut
10358
11325
  ? { jobs: c.carveOut.jobs.map((j) => ({ name: j.name, redDurationMs: j.redMs, branchDurationMs: j.branchMs })) }
10359
11326
  : null,
11327
+ // #474: the red job(s) proven only by a dry run of a main-only workflow — null otherwise.
11328
+ dryRun: c.dryRun ? { jobs: c.dryRun.jobs.slice() } : null,
11329
+ // #474: on a refusal, the dry run(s) that would supply the missing 2b evidence — what the real
11330
+ // ship dispatches; `--dry --json` only reports it. null when none would help.
11331
+ dryRunWanted: c.dryRunDispatch ? c.dryRunDispatch.map((d) => ({ ...d })) : null,
11332
+ // #510: the trunk-only red job(s) proven only by a workflow_dispatch run at the branch head — null otherwise.
11333
+ dispatch: c.dispatch ? { jobs: c.dispatch.jobs.slice() } : null,
11334
+ // #510: on a refusal, the workflow_dispatch run(s) that would supply the missing 2b evidence.
11335
+ dispatchWanted: c.dispatchCure ? c.dispatchCure.map((d) => ({ ...d })) : null,
11336
+ // #475/#476: the manifest change a cure was admitted with — `{scripts?, pins?}` — or null.
11337
+ admitted: c.admitted || null,
11338
+ // #477: condition 3 passed by progress past a prior exemption — `{healed, still}` — or null.
11339
+ progress: c.progress ? { healed: c.progress.healed.slice(), still: c.progress.still.slice() } : null,
10360
11340
  };
10361
11341
  }
10362
11342
 
11343
+ /** The dispatch input a dry-run-capable workflow declares (#474, templates/release-auto.yml). */
11344
+ const DRY_RUN_INPUT = 'dry_run';
11345
+
11346
+ /**
11347
+ * The workflows at `treeish` that offer a dry run (#474): a top-level `name:`, a `workflow_dispatch`
11348
+ * input named `dry_run`, and ci-cure's sentinel step text. All three, read statically at the BRANCH's
11349
+ * head — the copy a dispatch on that ref would run. A pre-#474 copy has no forced-dry mode and would
11350
+ * really publish if dispatched, which is exactly why this read gates every dispatch. `[]` on any
11351
+ * failed read: no capability is ever assumed.
11352
+ */
11353
+ function dryRunCapableWorkflows(repoAbs, treeish) {
11354
+ const ls = git.git(['ls-tree', '--name-only', `${treeish}:.github/workflows`], repoAbs);
11355
+ if (!ls.ok) return [];
11356
+ const out = [];
11357
+ for (const f of ls.stdout.split('\n').map((x) => x.trim()).filter((x) => /\.ya?ml$/.test(x))) {
11358
+ const r = git.git(['show', `${treeish}:.github/workflows/${f}`], repoAbs);
11359
+ if (!r.ok) continue;
11360
+ const name = workflowTriggers.workflowNameOf(r.stdout);
11361
+ if (!name || !r.stdout.includes(ciCure.DRY_RUN_STEP)) continue;
11362
+ if (!workflowTriggers.workflowDispatchInputs(r.stdout).includes(DRY_RUN_INPUT)) continue;
11363
+ out.push({ name, file: f });
11364
+ }
11365
+ return out;
11366
+ }
11367
+
11368
+ /**
11369
+ * The workflows at `treeish` a plain `workflow_dispatch` can run for the cure rule (#510): a top-level
11370
+ * `name:`, `workflow_dispatch` among the `on:` events, and NOT dry-run capable (those keep #474's path,
11371
+ * which forces dry mode — a plain dispatch of one would really publish). Read statically at the BRANCH's
11372
+ * head, the copy a dispatch on that ref runs. Whether it is branch CI rather than a main-only workflow is
11373
+ * gate (d) in ci-cure's `cureDispatchPlan`, read off the runs. `[]` on any failed read.
11374
+ */
11375
+ function dispatchableWorkflows(repoAbs, treeish) {
11376
+ const ls = git.git(['ls-tree', '--name-only', `${treeish}:.github/workflows`], repoAbs);
11377
+ if (!ls.ok) return [];
11378
+ const out = [];
11379
+ for (const f of ls.stdout.split('\n').map((x) => x.trim()).filter((x) => /\.ya?ml$/.test(x))) {
11380
+ const r = git.git(['show', `${treeish}:.github/workflows/${f}`], repoAbs);
11381
+ if (!r.ok) continue;
11382
+ const name = workflowTriggers.workflowNameOf(r.stdout);
11383
+ if (!name || r.stdout.includes(ciCure.DRY_RUN_STEP)) continue;
11384
+ if (!workflowTriggers.parseWorkflowOn(r.stdout).events.has('workflow_dispatch')) continue;
11385
+ out.push({ name, file: f });
11386
+ }
11387
+ return out;
11388
+ }
11389
+
11390
+ /**
11391
+ * Dispatch the workflow_dispatch run(s) a refused cure asked for (#510) — the REAL ship path only, the
11392
+ * same posture as `shipDispatchDryRuns` below. Skips a workflow that already has a `workflow_dispatch`
11393
+ * run at the branch head, whatever its status. Never waits: the job it runs may take hours, and ship's
11394
+ * measurement runs up to three times per invocation — the caller waits with `colab ci-wait` and re-runs.
11395
+ */
11396
+ function shipDispatchCure(repoAbs, branch, plan) {
11397
+ const head = git.git(['rev-parse', branch], repoAbs);
11398
+ const sha = head.ok ? head.stdout.trim() : '';
11399
+ const runs = sha ? git.ghRunsForCommit(repoAbs, branch, sha, 30) : null;
11400
+ for (const p of plan) {
11401
+ const existing = runs ? runs.filter((r) => r.workflowName === p.workflow && r.event === 'workflow_dispatch') : null;
11402
+ if (existing === null) {
11403
+ warn(` workflow_dispatch of ${p.workflow} NOT made: the runs at ${branch}'s head could not be read — run it yourself: ${p.command}`);
11404
+ continue;
11405
+ }
11406
+ if (existing.length) {
11407
+ const r = existing[0];
11408
+ 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.`);
11409
+ continue;
11410
+ }
11411
+ const d = git.ghWorkflowDispatch(repoAbs, p.file, branch, {});
11412
+ if (d.ok) {
11413
+ warn(` ↻ dispatched ${p.workflow} on ${branch} (#510) — it runs the trunk-only job(s) the branch push skipped. ` +
11414
+ `Wait with \`colab ci-wait --sha ${sha} --branch ${branch} --timeout <the job's usual length>\`, then re-run \`colab ship\`.`);
11415
+ } else {
11416
+ warn(` ${p.workflow} could NOT be dispatched (${d.detail}) — run it yourself: ${p.command}`);
11417
+ }
11418
+ }
11419
+ }
11420
+
11421
+ /**
11422
+ * Dispatch the dry run(s) a refused cure asked for (#474) — the REAL ship path only, never `--dry`,
11423
+ * never `--dry --json`, never from the measurement above (which runs up to three times per ship).
11424
+ * Skips a workflow that already has ANY run at the branch head, whatever its status: a queued run has
11425
+ * no jobs yet, so "job absent" alone would dispatch it twice. Never waits — the caller re-runs ship
11426
+ * once the run completes (code-ship B1a's bounded wait), the same no-polling stance as every other
11427
+ * read here.
11428
+ */
11429
+ function shipDispatchDryRuns(repoAbs, branch, plan) {
11430
+ const head = git.git(['rev-parse', branch], repoAbs);
11431
+ const runs = head.ok ? git.ghRunsForCommit(repoAbs, branch, head.stdout.trim(), 30) : null;
11432
+ for (const p of plan) {
11433
+ const existing = runs ? runs.filter((r) => r.workflowName === p.workflow) : null;
11434
+ if (existing === null) {
11435
+ warn(` dry run for ${p.workflow} NOT dispatched: the runs at ${branch}'s head could not be read — run it yourself: ${p.command}`);
11436
+ continue;
11437
+ }
11438
+ if (existing.length) {
11439
+ const r = existing[0];
11440
+ 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.`);
11441
+ continue;
11442
+ }
11443
+ const d = git.ghWorkflowDispatch(repoAbs, p.file, branch, { [DRY_RUN_INPUT]: 'true' });
11444
+ if (d.ok) {
11445
+ warn(` ↻ dispatched a dry run of ${p.workflow} on ${branch} (#474)${d.withInputs ? '' : ' — without the input, which GitHub refused; the ref forces dry mode'}. ` +
11446
+ 'Re-run `colab ship` once it completes (code-ship B1a\'s bounded wait) — it is the evidence this cure is missing.');
11447
+ } else {
11448
+ warn(` dry run for ${p.workflow} could NOT be dispatched (${d.detail}) — run it yourself: ${p.command}`);
11449
+ }
11450
+ }
11451
+ }
11452
+
10363
11453
  /**
10364
11454
  * Previews whether B0's merge (target INTO the branch) would conflict — WITHOUT touching the real
10365
11455
  * worktree, the branch, or the network beyond a fetch — so `ship --dry --json`'s "no hand-merge
@@ -10527,7 +11617,7 @@ function cmdShipDryJson(opts) {
10527
11617
  const gh = isGhUsable(repoAbs);
10528
11618
  const ciResultJson = shipCiCheck(repoAbs, gh, target, trunk,
10529
11619
  (redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
10530
- (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch));
11620
+ (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
10531
11621
  ciGrantPayloadVal = ciGrantPayload(ciResultJson);
10532
11622
  ciCurePayloadVal = ciCurePayload(ciResultJson);
10533
11623
  checks.push({ name: ciResultJson.name, ok: ciResultJson.ok, class: ciResultJson.class, detail: ciResultJson.detail });
@@ -10789,14 +11879,21 @@ function shipMode(repoAbs, target, branch, commits) {
10789
11879
  */
10790
11880
  function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
10791
11881
  const seen = new Set();
11882
+ const tr = tracker.forRepo(repoAbs);
10792
11883
  for (const start of closedIssues || []) {
10793
11884
  let child = start;
10794
11885
  for (let depth = 0; depth < 5; depth++) {
10795
- const view = git.ghIssueView(repoAbs, child, ['parent']);
11886
+ const view = tr.issueView(child, ['parent', 'url']);
10796
11887
  const pnum = view && view.parent && Number.isInteger(view.parent.number) ? view.parent.number : null;
10797
11888
  if (pnum === null || seen.has(pnum)) break;
11889
+ // #502: the parent's NUMBER means something only in the parent's own repository. A cross-repo
11890
+ // parent looked up here would read nothing (a misleading "could not read") or an unrelated
11891
+ // issue sharing the number — which could be classified and closed. Never evaluated from here.
11892
+ const rel = containerClose.parentRelation(view);
11893
+ if (rel.relation === 'other') { print(` container ${containerClose.parentRelationFinding(rel)} (#502)`); break; }
11894
+ if (rel.relation !== 'same') { warn(`container ${containerClose.parentRelationFinding(rel)}`); break; }
10798
11895
  seen.add(pnum);
10799
- const parent = git.ghIssueView(repoAbs, pnum, ['number', 'state', 'labels', 'body', 'subIssuesSummary']);
11896
+ const parent = tr.issueView(pnum, ['number', 'state', 'labels', 'body', 'subIssuesSummary']);
10800
11897
  const c = containerClose.classifyContainer(parent || null);
10801
11898
  if (c.verdict !== 'close') {
10802
11899
  const finding = containerClose.containerFinding({ ...c, number: c.number === null ? pnum : c.number });
@@ -10807,7 +11904,7 @@ function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
10807
11904
  const cm = git.ghIssueComment(repoAbs, pnum, body);
10808
11905
  if (!cm.ok) warnDeferred(`could not post the container-close comment on #${pnum} — left OPEN`);
10809
11906
  if (!cm.ok) break;
10810
- const r = git.run('gh', ['issue', 'close', String(pnum), '--reason', 'completed'], { cwd: repoAbs });
11907
+ const r = tr.issueClose(pnum, { reason: 'completed' });
10811
11908
  if (!r.ok) { warnDeferred(`could not close container #${pnum}: ${(r.stderr || '').split('\n')[0]}`); break; }
10812
11909
  print(` closed container #${pnum} — all ${c.total} sub-issue(s) closed (#371)`);
10813
11910
  for (const d of containerClose.containerDeliveryLabels(parent.labels)) warn(`container #${pnum} carried ${d} — a container has no deliverable of its own (#371)`);
@@ -10817,7 +11914,14 @@ function shipCloseSpentContainers(repoAbs, closedIssues, { sha, target } = {}) {
10817
11914
  }
10818
11915
 
10819
11916
  function shipJournalPlanFiles(repoAbs, issues) {
10820
- const plansDir = path.join(repoAbs, '.claude', 'plans');
11917
+ // #488: the configured plans dir first, then the legacy `.claude/plans/` — a plan written before
11918
+ // the switch is still journalled and deleted. One journal line per issue across both dirs: a
11919
+ // stray duplicate in the second dir is deleted without journalling the issue twice.
11920
+ const journalled = new Set();
11921
+ for (const plansDir of scratchDirs.planReadDirs(repoAbs)) shipJournalPlanDir(repoAbs, plansDir, issues, journalled);
11922
+ }
11923
+
11924
+ function shipJournalPlanDir(repoAbs, plansDir, issues, journalled) {
10821
11925
  let entries;
10822
11926
  try { entries = fs.readdirSync(plansDir); } catch (_) { return; } // no plans dir at all — nothing to do
10823
11927
  const issueSet = new Set(issues.map((n) => String(n)));
@@ -10834,13 +11938,17 @@ function shipJournalPlanFiles(repoAbs, issues) {
10834
11938
  const rm = txt.match(/^rung:\s*(.+)$/m); if (rm) rung = rm[1].trim();
10835
11939
  const cm = txt.match(/^cause:\s*(.+)$/m); if (cm) cause = cm[1].trim();
10836
11940
  } catch (_) { /* front matter is optional — the defaults above cover a plain rung-1 stub */ }
10837
- const lines = nums.map((num) => JSON.stringify({
11941
+ const fresh = nums.filter((num) => !journalled.has(num));
11942
+ const lines = fresh.map((num) => JSON.stringify({
10838
11943
  ts: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
10839
11944
  issue: Number(num), rung, cause, verdict: 'pass',
10840
- })).join('\n') + '\n';
11945
+ })).join('\n');
10841
11946
  try {
10842
- fs.mkdirSync(path.dirname(journalPath), { recursive: true });
10843
- fs.appendFileSync(journalPath, lines);
11947
+ if (lines) {
11948
+ fs.mkdirSync(path.dirname(journalPath), { recursive: true });
11949
+ fs.appendFileSync(journalPath, lines + '\n');
11950
+ }
11951
+ for (const num of fresh) journalled.add(num);
10844
11952
  fs.rmSync(planPath, { force: true }); // only after the journal write above landed
10845
11953
  } catch (e) {
10846
11954
  warnDeferred(`could not journal/delete the plan file "${name}" (${e.message}) — left in place`);
@@ -10902,7 +12010,7 @@ function shipEvidenceClose({ repoAbs, st, sess, target, trunk, gh, closeIssues,
10902
12010
  `write. The zero-diff fact was measured from git: ${mode.why}.${shipSess}`;
10903
12011
  const c = git.ghIssueComment(repoAbs, num, body);
10904
12012
  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 });
12013
+ const r = tracker.forRepo(repoAbs).issueClose(num, { reason: 'completed' });
10906
12014
  if (!r.ok) { skipped.push({ num, why: `gh issue close failed: ${(r.stderr || '').split('\n')[0]}` }); continue; }
10907
12015
  closed.push(num);
10908
12016
  print(` #${num} closed with evidence.`);
@@ -11157,6 +12265,8 @@ function cmdShipDirect(opts) {
11157
12265
  print(preOk ? '→ READY: preconditions pass. Re-run without --dry to close.' : '→ NOT READY: fix the ✗ rows above.');
11158
12266
  print(' Plan: no merge, no commit, no push · post evidence comment + CLOSE each issue · release the claims (and the checkout hold)');
11159
12267
  print(' Gate: every closing issue must already carry an evidence comment — checked at run time.');
12268
+ // #479: show BOTH halves of the split, so a wrong one is visible before the push.
12269
+ if (closeIssues.length) print(` Closes (closed by this ship): ${closeIssues.map((n) => '#' + n).join(' ')}`);
11160
12270
  if (refsIssues.length) print(` Refs (kept open, NOT closed): ${refsIssues.map((n) => '#' + n).join(' ')}`);
11161
12271
  return preOk ? 0 : 1;
11162
12272
  }
@@ -11186,6 +12296,19 @@ function readTargetCodeowners(repoAbs, target) {
11186
12296
  return null;
11187
12297
  }
11188
12298
 
12299
+ /**
12300
+ * #483: is this repo a fork, and which org owns it? The fork test is adopt's own (#449: a remote named
12301
+ * `upstream` whose URL differs from origin's), so adopt and ship never disagree about the shape; the
12302
+ * owner is read from this repo's remote URL. Either unknown → `{ fork: false }`, nothing is dropped.
12303
+ */
12304
+ function codeownersForkContext(repoAbs) {
12305
+ if (!adoptDetectFork(repoAbs)) return { fork: false, ownOrg: null };
12306
+ const name = git.remoteInfo(repoAbs).name || 'origin';
12307
+ const u = git.git(['remote', 'get-url', name], repoAbs);
12308
+ const ownOrg = u.ok ? codeowners.remoteOwner(u.stdout) : null;
12309
+ return { fork: !!ownOrg, ownOrg };
12310
+ }
12311
+
11189
12312
  function branchChangedPathsNoRenames(repoAbs, base, ref) {
11190
12313
  const r = git.git(['diff', '--name-only', '--no-renames', `${base}...${ref}`], repoAbs);
11191
12314
  return r.ok ? r.stdout.split('\n').map((s) => s.trim()).filter(Boolean) : null;
@@ -11229,21 +12352,30 @@ function shipDirectCoreReview(repoAbs, gh, trunk, since) {
11229
12352
  }
11230
12353
  }
11231
12354
  }
11232
- return codeowners.directVerdict({ files: [before, readTargetCodeowners(repoAbs, trunk)], authors, changed });
12355
+ return codeowners.directVerdict({ files: [before, readTargetCodeowners(repoAbs, trunk)], authors, changed, fork: codeownersForkContext(repoAbs) });
11233
12356
  }
11234
12357
 
11235
12358
  function shipCoreReview(repoAbs, gh, target, branch) {
11236
- const out = { active: false, inertReason: null, codeownersPath: null, warnings: [], corePaths: [],
12359
+ const out = { active: false, inertReason: null, codeownersPath: null, warnings: [], corePaths: [], ignoredOwners: [],
11237
12360
  pr: null, approval: null, headSha: null, authors: [], verdict: 'inert', detail: '' };
11238
12361
  const file = readTargetCodeowners(repoAbs, target);
11239
12362
  if (!file) { out.inertReason = `no CODEOWNERS on ${target}`; out.detail = `inert: ${out.inertReason}`; return out; }
11240
12363
  out.codeownersPath = file.path;
11241
- const { rules, warnings } = codeowners.parse(file.text);
11242
- out.warnings = warnings;
12364
+ const parsedFile = codeowners.parse(file.text);
12365
+ out.warnings = parsedFile.warnings;
12366
+ // #483: on a fork, teams of another org (inherited from the upstream) bind nothing here.
12367
+ const forkCtx = codeownersForkContext(repoAbs);
12368
+ const { rules, dropped } = codeowners.dropForeignTeams(parsedFile.rules, forkCtx);
12369
+ out.ignoredOwners = dropped;
12370
+ if (dropped.length) out.warnings = [...out.warnings, codeowners.foreignNote(dropped, forkCtx)];
11243
12371
  const parsed = branchName.parse(branch);
11244
12372
  out.authors = [...new Set([gh ? git.ghCurrentLogin() : null, parsed && parsed.login].filter(Boolean))];
11245
12373
  const inert = codeowners.inert(rules, out.authors);
11246
- if (inert.inert) { out.inertReason = inert.reason; out.detail = `inert: ${inert.reason}`; return out; }
12374
+ if (inert.inert) {
12375
+ out.inertReason = dropped.length ? `${inert.reason} once the fork's inherited foreign-org teams are ignored (#483)` : inert.reason;
12376
+ out.detail = `inert: ${out.inertReason}`;
12377
+ return out;
12378
+ }
11247
12379
  out.active = true;
11248
12380
  const ref = shipRefFor(repoAbs, branch);
11249
12381
  out.headSha = git.git(['rev-parse', ref], repoAbs).stdout || null;
@@ -11304,7 +12436,7 @@ function coreReviewPayload(cr) {
11304
12436
  if (!cr) return null;
11305
12437
  return {
11306
12438
  active: cr.active, verdict: cr.verdict, inertReason: cr.inertReason, codeownersPath: cr.codeownersPath,
11307
- corePaths: cr.corePaths.map((c) => c.path), headSha: cr.headSha,
12439
+ ignoredOwners: cr.ignoredOwners || [], corePaths: cr.corePaths.map((c) => c.path), headSha: cr.headSha,
11308
12440
  pr: cr.pr ? { number: cr.pr.number, url: cr.pr.url, state: cr.pr.state } : null,
11309
12441
  approval: cr.approval,
11310
12442
  };
@@ -11380,7 +12512,13 @@ function shipRefFor(repoAbs, branch) {
11380
12512
 
11381
12513
  function cmdShip(argv) {
11382
12514
  const opts = parseArgs(argv, {
11383
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--refs': 'refs', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch' },
12515
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch' },
12516
+ // #479: a repeated --refs used to keep only its LAST value, and every dropped issue then became a
12517
+ // `Closes` line on trunk — an issue meant to stay open, auto-closed by the push. --refs now
12518
+ // accumulates (a repeat is the same as one comma list); every OTHER value flag to ship refuses a
12519
+ // repeat (`once`), checked here before any git or GitHub call.
12520
+ lists: { '--refs': 'refs' },
12521
+ once: true,
11384
12522
  flags: { '--keep-worktree': 'keepWorktree', '--delete-branch': 'deleteBranch', '--keep-branch': 'keepBranch', '--dry': 'dry', '--json': 'json', '--direct': 'direct', '--adopt': 'adopt', '-h': 'help', '--help': 'help' },
11385
12523
  });
11386
12524
  if (opts.help) return print(HELP_SHIP);
@@ -11501,7 +12639,7 @@ function cmdShip(argv) {
11501
12639
  // ordinary green-trunk ship makes zero extra `gh` reads for a door nobody needs.
11502
12640
  const ciResult = shipCiCheck(repoAbs, gh, target, trunk,
11503
12641
  (redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
11504
- (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch));
12642
+ (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
11505
12643
  const ciOk = ciResult.ok;
11506
12644
  checks.push([ciResult.ok ? '✓' : '✗', ciResult.name, ciResult.detail]);
11507
12645
 
@@ -11792,6 +12930,16 @@ function cmdShip(argv) {
11792
12930
  }
11793
12931
  const dryOk = preOk && dryClosingConflicts.length === 0;
11794
12932
  print(dryOk ? '→ READY: preconditions pass. Re-run without --dry to ship.' : '→ NOT READY: fix the ✗ rows above.');
12933
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dryRunDispatch) {
12934
+ for (const d of ciResult.cureVerdict.dryRunDispatch) {
12935
+ 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.`);
12936
+ }
12937
+ }
12938
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dispatchCure) {
12939
+ for (const d of ciResult.cureVerdict.dispatchCure) {
12940
+ 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.`);
12941
+ }
12942
+ }
11795
12943
  if (mode.evidenceClose) {
11796
12944
  print(' Plan: no merge, no commit, no push · post evidence comment + CLOSE each issue · ' +
11797
12945
  (opts.keepWorktree ? 'keep worktree' : 'worktree rm') + ' (releases claims)');
@@ -11819,10 +12967,23 @@ function cmdShip(argv) {
11819
12967
  print(` ✗ "${c.keyword} #${c.num}" would close #${c.num} on merge — kept open by --refs; reword the commit before shipping.`);
11820
12968
  }
11821
12969
  }
12970
+ // #479: show BOTH halves of the split, so a wrong one is visible before the push.
12971
+ if (closeIssues.length) print(` Closes (closed by this ship): ${closeIssues.map((n) => '#' + n).join(' ')}`);
11822
12972
  if (refsIssues.length) print(` Refs (kept open, NOT closed): ${refsIssues.map((n) => '#' + n).join(' ')}`);
11823
12973
  return dryOk ? 0 : 1;
11824
12974
  }
11825
- if (!preOk) { process.stderr.write('✗ Aborting: one or more preconditions failed (see ✗ above). Nothing was pushed.\n'); return 1; }
12975
+ if (!preOk) {
12976
+ // #474: the cure is missing only a main-only workflow's run, and that workflow offers a dry run —
12977
+ // dispatch it now (once), so the re-run has the evidence. Never on --dry: that returned above.
12978
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dryRunDispatch && gh) {
12979
+ shipDispatchDryRuns(repoAbs, sess.branch, ciResult.cureVerdict.dryRunDispatch);
12980
+ }
12981
+ // #510: same, for a branch workflow whose red job the push skipped — a plain workflow_dispatch.
12982
+ if (!ciOk && ciResult.cureVerdict && ciResult.cureVerdict.dispatchCure && gh) {
12983
+ shipDispatchCure(repoAbs, sess.branch, ciResult.cureVerdict.dispatchCure);
12984
+ }
12985
+ process.stderr.write('✗ Aborting: one or more preconditions failed (see ✗ above). Nothing was pushed.\n'); return 1;
12986
+ }
11826
12987
 
11827
12988
  // ---- (b3) evidence-close: the whole B0–B2 sequence is skipped, because there is nothing to merge ----
11828
12989
  if (mode.evidenceClose) return shipEvidenceClose({
@@ -11925,7 +13086,8 @@ function cmdShip(argv) {
11925
13086
  if (coreReview.verdict === 'approved') {
11926
13087
  const reviewed = new Set(coreReview.corePaths.map((c) => c.path));
11927
13088
  const nowChanged = branchChangedPathsNoRenames(repoAbs, mergeRef, sess.branch) || [];
11928
- const { rules } = codeowners.parse((readTargetCodeowners(repoAbs, target) || {}).text || '');
13089
+ const { rules } = codeowners.dropForeignTeams(
13090
+ codeowners.parse((readTargetCodeowners(repoAbs, target) || {}).text || '').rules, codeownersForkContext(repoAbs));
11929
13091
  const unreviewed = codeowners.corePaths(rules, nowChanged).filter((c) => !reviewed.has(c.path));
11930
13092
  if (unreviewed.length) {
11931
13093
  cleanupEphemeral();
@@ -11948,7 +13110,7 @@ function cmdShip(argv) {
11948
13110
  if (gh) {
11949
13111
  const ciResultB1 = shipCiCheck(repoAbs, gh, target, trunk,
11950
13112
  (redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
11951
- (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch));
13113
+ (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
11952
13114
  if (!ciResultB1.ok) {
11953
13115
  cleanupEphemeral();
11954
13116
  process.stderr.write(`✗ B1: CI for ${target} is no longer green — aborting before merge. Nothing pushed. (${ciResultB1.detail})\n`);
@@ -12412,12 +13574,16 @@ function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, re
12412
13574
  // its last member.
12413
13575
  if (gh) {
12414
13576
  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'}`);
13577
+ // #448: search says zero → a non-search read must agree before the repo-wide delete.
13578
+ const t = groupLabels.teardownSpentGroupLabel(gl, {
13579
+ searchOpen: (name) => git.ghIssueListByLabel(repoAbs, name, 'open', ['number']),
13580
+ confirmOpen: (name) => git.ghOpenIssueNumbersByLabel(repoAbs, name),
13581
+ deleteLabel: (name) => git.ghLabelDelete(repoAbs, name),
13582
+ });
13583
+ if (t.reason === 'open') continue; // still binds the remainder — leave it
13584
+ if (t.action === 'keep') { warn(groupLabels.keptReason(gl, t)); continue; }
13585
+ if (t.deleted) print(` deleted spent group label ${gl} (every member now closed)`);
13586
+ else warn(`could not delete spent group label ${gl}: ${t.error}`);
12421
13587
  }
12422
13588
  }
12423
13589
 
@@ -12800,9 +13966,28 @@ function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opt
12800
13966
  const headNow = git.git(['rev-parse', 'HEAD'], repoAbs).stdout;
12801
13967
  if (headNow === head) git.git(['reset', '--hard', preMergeSha], repoAbs); // #322: our own merge, put back
12802
13968
  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;
13969
+ // #509: a failed push is not proof trunk moved — re-read the remote trunk before saying so.
13970
+ const ls = git.run('git', ['ls-remote', remote, `refs/heads/${trunk}`], { cwd: repoAbs, timeoutMs: 60_000 });
13971
+ const remoteNow = ls.ok ? ((ls.stdout || '').split('\n')[0] || '').split('\t')[0].trim() : null;
13972
+ const why = shipBatch.landPushFailure({ stderr: push.stderr, remoteNow, base });
13973
+ const rolled = `nothing landed; ${trunk} rolled back to ${shortSha(preMergeSha)}`;
13974
+ const echo = () => { for (const l of why.lines) print(` │ ${l}`); };
13975
+ if (why.kind === 'trunk-moved') {
13976
+ print(`⏸ ship-batch: trunk moved during land (${remote}/${trunk} ${shortSha(base)} → ${shortSha(remoteNow)}) — ${rolled}.`);
13977
+ print(' Run this command again: it sees the moved trunk and rebuilds the batch on it.');
13978
+ } else if (why.kind === 'unreachable') {
13979
+ print(`⏸ ship-batch: the push failed and ${remote}/${trunk} could not be re-read to say why — ${rolled}. The push said:`);
13980
+ echo();
13981
+ print(` Run this command again once ${remote} answers; it re-reads trunk before deciding anything.`);
13982
+ } else {
13983
+ const who = why.kind === 'remote-rejected'
13984
+ ? `${remote} rejected the update`
13985
+ : 'the push was refused before it reached the remote (a local pre-push hook?)';
13986
+ print(`✗ ship-batch: ${who} — ${remote}/${trunk} did NOT move (still ${shortSha(base)}); ${rolled}. The push said:`);
13987
+ echo();
13988
+ print(' This is not a moved trunk: re-running hits the same refusal. Fix what the output above names, then run this command again.');
13989
+ }
13990
+ return why.exit;
12806
13991
  }
12807
13992
  print(' pushed.');
12808
13993
  deferredCollector = [];
@@ -12887,6 +14072,249 @@ function shipBatchMemberTail({ repoAbs, doc, trunk, sess, sha, closeIssues, refs
12887
14072
  // decides and deletes is one bug away from deleting on an `unknown`.
12888
14073
  // ---------------------------------------------------------------------------
12889
14074
 
14075
+ // trunk-ci — the trunk-CI verdict `colab ship` computes, read-only (#463). code-triage's §0 "red
14076
+ // trunk nobody owns" check and §5's "Trunk CI is alive" bullet call this instead of keeping a
14077
+ // `gh run list` filter of their own — two rules for one question disagreed, and the red went
14078
+ // unowned (a sha with CI green and a release workflow red read GREEN to triage, not-green to ship).
14079
+ const TRUNK_CI_TTL_DEFAULT_SEC = 45;
14080
+ const HELP_TRUNK_CI = `colab trunk-ci [--repo <path>] [--fresh] [--json]
14081
+
14082
+ Print the trunk-CI verdict \`colab ship\` would compute for the trunk's CURRENT remote head —
14083
+ the same read (shipCiCheck's readCiVerdict): by branch, re-read by commit when empty, runs from
14084
+ workflows the repo does not own dropped (#451), each workflow judged by its newest run (#461).
14085
+ Read-only: no claim, no label, no write.
14086
+
14087
+ Only runs that VERIFY the code are judged (#503): push / pull_request / merge_group triggered.
14088
+ A run of any other trigger at the same sha — a workflow_run release (release-auto.yml), a
14089
+ scheduled finalize, a dispatch, a deploy — comes after the verdict and is set aside and named in
14090
+ the detail (--json: setAside). Override in .github/project.yml, by workflow name:
14091
+ ship-gate-workflows: [CI] exactly these workflows count, whatever their trigger
14092
+ ship-ignore-workflows: [Deploy] set these aside too, even when push-triggered
14093
+
14094
+ The first output word is one verdict:
14095
+ GREEN every judged workflow's newest run at the sha succeeded — ship's row would pass
14096
+ RED a judged run completed and did not succeed — trunk is red
14097
+ PENDING a judged run is still in flight (or the sha is minutes old with no run yet)
14098
+ WEDGED a run that will never move on its own (zero jobs / hours unmoving, #155)
14099
+ NONE no repo-owned run exists at the sha — CI not wired or never started
14100
+ UNREADABLE gh unusable or the read failed — never "green"
14101
+
14102
+ Exemption doors (the cure rule, a ci-grant) are NOT applied: they let one branch past a red
14103
+ trunk, they do not make the trunk green, and the red still needs an owner.
14104
+
14105
+ A GREEN whose suite the CI guard skipped because a green run of the same workflow already
14106
+ passed an identical tree (#493) names that run in its detail ("relied on <url>"). If the cited
14107
+ head is local and its tree differs from trunk's, the read is RED: trunk is untested.
14108
+
14109
+ Cost (#495): one REST read of the runs at the sha (\`actions/runs?head_sha=\`), plus one
14110
+ check-runs read on a GREEN. No auth probe in front of it — the read is the probe, and an
14111
+ UNREADABLE explains which credential/remote condition failed. The verdict is cached per
14112
+ trunk+sha for ${TRUNK_CI_TTL_DEFAULT_SEC}s in the repo's git dir, shared by every session on the
14113
+ checkout (COLAB_TRUNK_CI_TTL=<sec> overrides, 0 disables; --fresh skips the cache for one read).
14114
+ To WAIT for CI, use \`colab ci-wait\` — never a loop around this command.
14115
+
14116
+ --fresh ignore a cached verdict (still refreshes the cache)
14117
+ --json { verdict, sha, ok, class, detail, trunk[, cited: [<run url>…] on a #493 skip][, cachedAgeSec] }
14118
+ Exit 0 whenever a verdict was read (whatever it is); 2 on UNREADABLE.`;
14119
+
14120
+ /** Map readCiVerdict's result to the closed trunk-ci vocabulary. Pure — exported for tests. */
14121
+ function trunkCiToken(r) {
14122
+ if (!r || !r.run) return 'UNREADABLE';
14123
+ if (r.verdict.ok) return 'GREEN';
14124
+ const st = r.run.status;
14125
+ if (st === 'none') return r.verdict.class === SELF_CLEARING ? 'PENDING' : 'NONE';
14126
+ if (st === 'completed') return 'RED';
14127
+ return r.verdict.class === HUMAN_GATED ? 'WEDGED' : 'PENDING';
14128
+ }
14129
+
14130
+ function cmdTrunkCi(argv) {
14131
+ const opts = parseArgs(argv, {
14132
+ values: { '--repo': 'repo' },
14133
+ flags: { '--json': 'json', '--fresh': 'fresh', '-h': 'help', '--help': 'help' },
14134
+ });
14135
+ if (opts.help) return print(HELP_TRUNK_CI);
14136
+ const repoAbs = resolveRepo(opts);
14137
+ if (!git.repoRoot(repoAbs)) throw new UserError(`${repoAbs} is not a git repo`);
14138
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
14139
+ if (!trunk) throw new UserError('cannot resolve trunk — no `trunk:` in .github/project.yml and no origin/HEAD');
14140
+
14141
+ // #495: the cache key is the trunk's CURRENT remote head — read with `git ls-remote`, which is the
14142
+ // git protocol, not the REST quota — so a new push is never answered from an older sha's verdict.
14143
+ const cache = trunkCiCache(repoAbs);
14144
+ const headSha = remoteHeadSha(repoAbs, trunk);
14145
+ const key = headSha ? `${trunk}@${headSha}` : null;
14146
+ let out = key && !opts.fresh ? cache.get(key) : null;
14147
+ if (!out) {
14148
+ // #495: no `gh auth status` probe in front of the read (it costs a REST + a GraphQL call per
14149
+ // process, and trunk-ci runs as a fresh process each time). The read itself proves the credential;
14150
+ // only an UNREADABLE pays for the explanation.
14151
+ const gh = git.ghInstalled() && !!git.remoteUrl(repoAbs);
14152
+ const r = readCiVerdict(repoAbs, gh, trunk, trunk);
14153
+ const verdict = trunkCiToken(r);
14154
+ const sha = r.run ? r.run.sha || null : null;
14155
+ let detail = r.verdict.detail;
14156
+ if (verdict === 'UNREADABLE' && gh && !git.ghState().ok) detail += ` (${ghUnusableWhy(repoAbs)})`;
14157
+ out = { verdict, trunk, sha, ok: r.verdict.ok, class: r.verdict.class || null, detail,
14158
+ ...(r.verdict.treeGreen ? { cited: r.verdict.treeGreen } : {}),
14159
+ ...(r.run && Array.isArray(r.run.setAside) && r.run.setAside.length ? { setAside: r.run.setAside } : {}) };
14160
+ if (key && verdict !== 'UNREADABLE' && sha === headSha) cache.put(key, out);
14161
+ }
14162
+ if (opts.json) {
14163
+ print(JSON.stringify(out, null, 2));
14164
+ } else {
14165
+ const age = out.cachedAgeSec !== undefined ? ` (cached ${out.cachedAgeSec}s ago)` : '';
14166
+ print(`${out.verdict} ${trunk}${out.sha ? `@${shortSha(out.sha)}` : ''} — ${out.detail}${age}`);
14167
+ }
14168
+ return out.verdict === 'UNREADABLE' ? 2 : 0;
14169
+ }
14170
+
14171
+ /** `git ls-remote <remote> refs/heads/<branch>` → sha, or null. Git protocol — no REST quota. */
14172
+ function remoteHeadSha(repoAbs, branch) {
14173
+ const remote = git.remoteInfo(repoAbs).name || 'origin';
14174
+ const r = git.git(['ls-remote', remote, `refs/heads/${branch}`], repoAbs);
14175
+ if (!r.ok) return null;
14176
+ return (r.stdout.split('\n')[0] || '').split('\t')[0].trim() || null;
14177
+ }
14178
+
14179
+ /**
14180
+ * #495: the trunk-ci verdict cache — `<git common dir>/colab-trunk-ci.json`, so every session and
14181
+ * worktree on one checkout shares it. Keyed by `<trunk>@<sha>`; an entry older than the TTL is a
14182
+ * miss. Best effort both ways: an unreadable/unwritable file is simply no cache.
14183
+ */
14184
+ function trunkCiCache(repoAbs) {
14185
+ const env = process.env.COLAB_TRUNK_CI_TTL;
14186
+ const ttl = env !== undefined && env !== '' && Number.isFinite(Number(env)) ? Number(env) : TRUNK_CI_TTL_DEFAULT_SEC;
14187
+ const dir = git.git(['rev-parse', '--path-format=absolute', '--git-common-dir'], repoAbs);
14188
+ const file = dir.ok && dir.stdout ? path.join(dir.stdout.trim(), 'colab-trunk-ci.json') : null;
14189
+ const load = () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')) || {}; } catch (_) { return {}; } };
14190
+ return {
14191
+ get(key) {
14192
+ if (!file || ttl <= 0) return null;
14193
+ const e = load()[key];
14194
+ if (!e || !e.at || !e.out) return null;
14195
+ const age = Math.floor((Date.now() - e.at) / 1000);
14196
+ return age >= 0 && age < ttl ? { ...e.out, cachedAgeSec: age } : null;
14197
+ },
14198
+ put(key, out) {
14199
+ if (!file || ttl <= 0) return;
14200
+ const now = Date.now();
14201
+ const all = load();
14202
+ for (const k of Object.keys(all)) if (!all[k] || now - all[k].at > ttl * 1000) delete all[k];
14203
+ all[key] = { at: now, out };
14204
+ try {
14205
+ const tmp = `${file}.${process.pid}.tmp`;
14206
+ fs.writeFileSync(tmp, JSON.stringify(all));
14207
+ fs.renameSync(tmp, file);
14208
+ } catch (_) { /* no cache, not an error */ }
14209
+ },
14210
+ };
14211
+ }
14212
+
14213
+ // ci-wait — THE way to wait for CI (#495). Agents' hand-rolled `sleep N; gh run …` loops spent ~88%
14214
+ // of a shared identity's REST quota in one measured hour; this waits with backoff, conditional
14215
+ // requests, a deadline, and a distinct exit code for every way a wait can end.
14216
+ const HELP_CI_WAIT = `colab ci-wait <run-id> | --sha <sha> [--branch <b>] [--repo <path>] [--timeout <dur>] [--json]
14217
+
14218
+ Wait for CI and exit with its outcome. The ONE way to wait for a run: never hand-roll a
14219
+ \`sleep N; gh run view\` loop, never run two waits for the same run, never hide gh's stderr.
14220
+
14221
+ <run-id> wait for one workflow run (actions/runs/<id>)
14222
+ --sha <sha> wait for EVERY repo-owned workflow at the sha (the verdict colab ship reads:
14223
+ newest run per workflow, dynamic workflows dropped — #451/#461; only runs that
14224
+ verify the code, so a post-CI release/deploy run is set aside — #503); a sha
14225
+ with no run yet counts as pending until the deadline
14226
+ --branch <b> narrow --sha to runs on that branch
14227
+ --timeout <d> deadline: 45m (default), 90s, 1h, or seconds
14228
+
14229
+ Polls at 0s, then +30s, +60s, +120s, +120s … until the deadline. Every poll after the first is a
14230
+ conditional request (If-None-Match); a 304 is not counted against the REST rate limit. A 15-minute
14231
+ run costs about 10 requests. One wait per run per checkout: a second waiter is refused.
14232
+
14233
+ Exit codes — branch on these, never on the text:
14234
+ 0 GREEN the run (every judged run at the sha) succeeded
14235
+ 1 RED completed and did not succeed
14236
+ 2 usage bad arguments
14237
+ 3 TIMEOUT the deadline passed while still pending
14238
+ 4 RATE_LIMITED GitHub refused for quota (403/429) — the wait ENDS, it does not retry
14239
+ 5 UNKNOWN a read failed or returned a state it cannot classify
14240
+ 6 ALREADY_WAITING another live ci-wait on this checkout holds the same run/sha
14241
+
14242
+ It prints the wait it did: outcome, elapsed time, polls, and how many were 304s.
14243
+ --json { outcome, exit, target, polls, notModified, waitedSec, detail, status, conclusion, url }`;
14244
+
14245
+ function cmdCiWait(argv) {
14246
+ const opts = parseArgs(argv, {
14247
+ values: { '--repo': 'repo', '--sha': 'sha', '--branch': 'branch', '--timeout': 'timeout' },
14248
+ flags: { '--json': 'json', '-h': 'help', '--help': 'help' },
14249
+ });
14250
+ if (opts.help) return print(HELP_CI_WAIT);
14251
+ const runId = opts._ && opts._[0];
14252
+ if ((runId ? 1 : 0) + (opts.sha ? 1 : 0) !== 1 || (runId && !/^\d+$/.test(runId)) || (opts.branch && !opts.sha)) {
14253
+ warn('ci-wait takes exactly one of <run-id> (numeric) or --sha <sha> [--branch <b>]');
14254
+ return ciWait.EXIT.USAGE;
14255
+ }
14256
+ const deadlineSec = opts.timeout !== undefined ? ciWait.parseDuration(opts.timeout) : ciWait.DEFAULT_DEADLINE_SEC;
14257
+ if (!deadlineSec) { warn(`--timeout: cannot read "${opts.timeout}" (try 45m, 90s, 1h)`); return ciWait.EXIT.USAGE; }
14258
+ const repoAbs = resolveRepo(opts);
14259
+ if (!git.ghInstalled()) { warn('gh is not installed — cannot read CI'); return ciWait.EXIT.UNKNOWN; }
14260
+
14261
+ const target = runId ? `run ${runId}` : `sha ${shortSha(opts.sha)}${opts.branch ? ` on ${opts.branch}` : ''}`;
14262
+ const apiPath = runId
14263
+ ? `repos/{owner}/{repo}/actions/runs/${runId}`
14264
+ : `repos/{owner}/{repo}/actions/runs?head_sha=${encodeURIComponent(opts.sha)}${opts.branch ? `&branch=${encodeURIComponent(opts.branch)}` : ''}&per_page=100`;
14265
+
14266
+ const gitDir = git.git(['rev-parse', '--path-format=absolute', '--git-common-dir'], repoAbs);
14267
+ const lock = gitDir.ok ? ciWait.acquireLock(path.join(gitDir.stdout.trim(), 'colab-ci-wait'), runId || `${opts.sha}-${opts.branch || ''}`) : { ok: true, release: () => {} };
14268
+ if (!lock.ok) {
14269
+ warn(`another ci-wait (pid ${lock.holder}) is already waiting on ${target} in this checkout — read its result, do not start a second wait`);
14270
+ return ciWait.EXIT.ALREADY_WAITING;
14271
+ }
14272
+
14273
+ const verifyPolicy = verifyRuns.parsePolicy(projectDoc(repoAbs));
14274
+ const poll = (etag) => {
14275
+ const r = git.ghApiConditional(repoAbs, apiPath, etag);
14276
+ if (r.kind !== 'ok') return r;
14277
+ let summary;
14278
+ if (runId) {
14279
+ summary = { status: r.json.status, conclusion: r.json.conclusion || null, url: r.json.html_url || null };
14280
+ } else {
14281
+ const rows = Array.isArray(r.json.workflow_runs) ? r.json.workflow_runs.map(ciWait.restRow).filter((x) => x.headSha === opts.sha) : null;
14282
+ if (!rows) return { kind: 'error', status: r.status, detail: 'response has no workflow_runs' };
14283
+ // #503: the same verifying-runs policy ship reads — a wait on trunk's head ends when the CI
14284
+ // that verifies the code ends, not when the post-CI release run does.
14285
+ summary = git.summarizeRunsForCommit(rows, opts.sha, { verifying: verifyPolicy });
14286
+ const pick = rows.find((x) => x.databaseId === summary.databaseId);
14287
+ summary = { ...summary, url: pick ? pick.url : null };
14288
+ }
14289
+ return { ...r, summary, state: ciWait.runState(summary) };
14290
+ };
14291
+
14292
+ 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`);
14293
+ let res;
14294
+ try {
14295
+ res = ciWait.waitLoop({
14296
+ poll, sleep: ciWait.sleepSync, deadlineSec,
14297
+ 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)' : ''}\n`); },
14298
+ });
14299
+ } finally {
14300
+ lock.release();
14301
+ }
14302
+ const s = (res.last && res.last.summary) || {};
14303
+ const code = ciWait.EXIT[res.outcome];
14304
+ const out = {
14305
+ outcome: res.outcome, exit: code, target, polls: res.polls, notModified: res.notModified,
14306
+ waitedSec: Math.round(res.waitedMs / 1000), detail: res.detail || null,
14307
+ status: s.status || null, conclusion: s.conclusion || null, url: s.url || null,
14308
+ ...(Array.isArray(s.setAside) && s.setAside.length ? { setAside: s.setAside } : {}),
14309
+ };
14310
+ if (opts.json) print(JSON.stringify(out, null, 2));
14311
+ else {
14312
+ print(`${res.outcome} ${target} — waited ${ciWait.fmtDuration(res.waitedMs)}, ${res.polls} poll(s), ${res.notModified} of them 304` +
14313
+ `${s.status ? ` · ${s.status}${s.conclusion ? `/${s.conclusion}` : ''}` : ''}${s.url ? ` · ${s.url}` : ''}${res.detail ? ` — ${res.detail}` : ''}${verifyRuns.setAsideNote(s.setAside)}`);
14314
+ }
14315
+ return code;
14316
+ }
14317
+
12890
14318
  const HELP_LANDED = `colab landed [--repo <path>] [--worktree <name> | --branch <br>] [--base <br>] [--all] [--json]
12891
14319
 
12892
14320
  Has this branch's work already landed on its base? The shared answer behind code-sweep's buckets
@@ -13230,11 +14658,12 @@ function cmdDeliver(argv) {
13230
14658
  if (!tip || !ownerTip) return fail(`${remote}/${trunk} or ${remote}/${owner.branch} does not resolve after the fetch`);
13231
14659
 
13232
14660
  // 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 });
14661
+ const r = tracker.forRepo(repoAbs).prList({
14662
+ base: owner.branch, head: trunk, state: 'all', limit: 50, fields: ['number', 'url', 'state', 'mergedAt', 'headRefOid', 'title'],
14663
+ });
13235
14664
  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'); }
14665
+ const list = r.stdout ? r.data : []; // an empty reply is no PRs here, as it always was
14666
+ if (list === null) return fail('gh pr list returned unparseable JSON');
13238
14667
  const prs = ownerBranch.classifyPrs(list);
13239
14668
 
13240
14669
  // 3. the undelivered range: since the last merged delivery's head when that head is still on
@@ -13286,7 +14715,7 @@ function cmdDeliver(argv) {
13286
14715
  return 1;
13287
14716
  }
13288
14717
  if (d.action === 'refresh') {
13289
- const e = git.run('gh', ['pr', 'edit', String(prs.open.number), '--title', text.title, '--body', text.body], { cwd: repoAbs });
14718
+ const e = tracker.forRepo(repoAbs).prEdit(prs.open.number, { title: text.title, body: text.body });
13290
14719
  if (!e.ok) return fail(`could not refresh PR #${prs.open.number}: ${(e.stderr || '').split('\n')[0]}`);
13291
14720
  out.done = `refreshed PR #${prs.open.number} (${prs.open.url || ''}) — waiting on the owner`;
13292
14721
  } else {
@@ -13695,7 +15124,7 @@ Commands:
13695
15124
  migration-grant <issue> --branch B | --revoke | --list [--json] human-only ship migration exemption (#98)
13696
15125
  decision <issue> --record --ruled-by N | --reopen --ruled-by N | --list [--json]
13697
15126
  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)
15127
+ ci-grant <issue> --branch B | --revoke | --list [--json] ship trunk-CI-green exemption: human, or ci-reviewer under opt-in (#105, #504)
13699
15128
  claims [--json] [--sync] list / reconcile with GitHub
13700
15129
 
13701
15130
  port alloc [--count N] [--range A-B] [--worktree N|--claim I|--label S]
@@ -13710,6 +15139,12 @@ Commands:
13710
15139
  code-wrap Phase B → the branch's recorded base (trunk, or a
13711
15140
  declared line). --json (--dry only): machine-readable
13712
15141
  preconditions with a closed refusal-class vocabulary (#77)
15142
+ trunk-ci [--fresh] [--json] the trunk-CI verdict ship computes, read-only (#463):
15143
+ GREEN | RED | PENDING | WEDGED | NONE | UNREADABLE
15144
+ (cached per sha ~45s in .git — #495)
15145
+ ci-wait <run-id> | --sha S [--branch B] [--timeout D] [--json]
15146
+ WAIT for CI with backoff + conditional requests (#495);
15147
+ exit 0 green · 1 red · 3 timeout · 4 rate-limited · 5 unknown
13713
15148
  landed [--worktree N | --branch B | --all] [--base B] [--json] has this work already landed?
13714
15149
  (the shared rule behind code-sweep's buckets — correct
13715
15150
  across squash merges, where "commits ahead" is not)
@@ -13797,6 +15232,8 @@ function main(argv) {
13797
15232
  case 'worktrees': return cmdWorktrees(rest);
13798
15233
  case 'ship': return cmdShip(rest);
13799
15234
  case 'landed': return cmdLanded(rest);
15235
+ case 'trunk-ci': return cmdTrunkCi(rest);
15236
+ case 'ci-wait': return cmdCiWait(rest);
13800
15237
  case 'holders': return cmdHolders(rest);
13801
15238
  case 'promote': return cmdPromote(rest);
13802
15239
  case 'deliver': return cmdDeliver(rest);