@futurelastic/colab-handbook 0.0.0-bootstrap.0 → 1.12.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +310 -3
  3. package/README.vi.md +280 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +137 -0
  22. package/templates/release-auto.yml +475 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13790 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +259 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify.js +188 -0
  63. package/tools/lib/npm-publish-guard.js +242 -0
  64. package/tools/lib/orphan-worktree.js +127 -0
  65. package/tools/lib/owner-branch.js +182 -0
  66. package/tools/lib/place.js +782 -0
  67. package/tools/lib/ports.js +167 -0
  68. package/tools/lib/procs.js +185 -0
  69. package/tools/lib/readiness.js +240 -0
  70. package/tools/lib/records.js +185 -0
  71. package/tools/lib/refs-brake.js +95 -0
  72. package/tools/lib/release-channel.js +99 -0
  73. package/tools/lib/release-cut.js +822 -0
  74. package/tools/lib/release-finalize.js +521 -0
  75. package/tools/lib/release-policy.js +358 -0
  76. package/tools/lib/release-tag.js +225 -0
  77. package/tools/lib/ship-batch.js +277 -0
  78. package/tools/lib/ship-roles.js +71 -0
  79. package/tools/lib/ship-target-sync.js +181 -0
  80. package/tools/lib/shipguard.js +317 -0
  81. package/tools/lib/shipped-branch.js +56 -0
  82. package/tools/lib/solo.js +213 -0
  83. package/tools/lib/squash.js +515 -0
  84. package/tools/lib/stale-base.js +70 -0
  85. package/tools/lib/stamp.js +740 -0
  86. package/tools/lib/state.js +262 -0
  87. package/tools/lib/teardown.js +83 -0
  88. package/tools/lib/trust-humans.js +104 -0
  89. package/tools/lib/util.js +98 -0
  90. package/tools/lib/wake.js +188 -0
  91. package/tools/lib/workflow-triggers.js +273 -0
  92. package/tools/lib/writes-authority.js +237 -0
  93. package/tools/lib/yaml.js +101 -0
  94. package/bin/cli.js +0 -3
@@ -0,0 +1,1059 @@
1
+ 'use strict';
2
+ /**
3
+ * Thin wrappers over `git` and `gh` via child_process. No dependencies.
4
+ * Every function degrades gracefully: git/gh missing, no remote, not a repo — return null/false,
5
+ * never throw for "environment doesn't have it". Real failures (bad args) still surface.
6
+ */
7
+
8
+ const { spawnSync } = require('child_process');
9
+ const path = require('path');
10
+
11
+ /**
12
+ * @param {object} [opts]
13
+ * @param {number} [opts.timeoutMs] - bound how long we'll wait (see #62: `git worktree remove` on
14
+ * a slow/synced volume, or a hook script blocked on a dead network call, used to hang forever
15
+ * with NO output — indistinguishable from slow-but-working). Omit for the historical unbounded
16
+ * behavior; every call site that can plausibly block on something outside the repo should pass one.
17
+ */
18
+ function run(cmd, args, opts = {}) {
19
+ const { timeoutMs, ...spawnOpts } = opts;
20
+ const res = spawnSync(cmd, args, { encoding: 'utf8', ...(timeoutMs ? { timeout: timeoutMs } : {}), ...spawnOpts });
21
+ const timedOut = !!(res.error && res.error.code === 'ETIMEDOUT');
22
+ return {
23
+ ok: res.status === 0 && !timedOut,
24
+ code: res.status,
25
+ stdout: (res.stdout || '').trim(),
26
+ stderr: timedOut ? `timed out after ${timeoutMs}ms with no output` : (res.stderr || '').trim(),
27
+ error: res.error || null,
28
+ timedOut,
29
+ };
30
+ }
31
+
32
+ function git(args, cwd, opts = {}) {
33
+ return run('git', args, { ...(cwd ? { cwd } : {}), ...opts });
34
+ }
35
+
36
+ /** Absolute repo root for a path (default cwd), or null if not a git repo. */
37
+ function repoRoot(cwd) {
38
+ const r = git(['rev-parse', '--show-toplevel'], cwd);
39
+ return r.ok ? r.stdout : null;
40
+ }
41
+
42
+ /**
43
+ * The MAIN working tree's root, even when `cwd` is inside a linked worktree.
44
+ *
45
+ * `repoRoot` answers "which tree am I standing in", which is a different question and the wrong
46
+ * one for anything keyed by repo identity. Claims, ports and worktree records are all stored
47
+ * under the main repo path, so resolving from inside a worktree used to miss every one of them:
48
+ * `colab ship` composed its squash message with an EMPTY issue list and never emitted `Closes #N`,
49
+ * silently, while the issue stayed open with its code merged.
50
+ *
51
+ * `--git-common-dir` is the shared `.git` for every worktree of a repo, so its parent is the main
52
+ * tree. Falls back to `repoRoot` whenever the layout is not the ordinary one (bare repos, a
53
+ * `.git` file that is not named `.git`) rather than guessing.
54
+ */
55
+ function mainRepoRoot(cwd) {
56
+ let dir = null;
57
+ // --path-format needs git >= 2.31; fall back to resolving the relative answer ourselves.
58
+ const abs = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);
59
+ if (abs.ok && abs.stdout) dir = abs.stdout;
60
+ else {
61
+ const rel = git(['rev-parse', '--git-common-dir'], cwd);
62
+ if (rel.ok && rel.stdout) dir = path.resolve(cwd || process.cwd(), rel.stdout);
63
+ }
64
+ if (dir && path.basename(dir) === '.git') return path.dirname(dir);
65
+ return repoRoot(cwd);
66
+ }
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // Which remote (#301) — the ONE place colab decides it. Every fetch, push, ls-remote,
70
+ // remote-tracking ref and remote-naming message routes through here instead of the literal
71
+ // `origin`. The first matching rule wins:
72
+ // 1. `git config colab.remote <name>` — the explicit, per-clone override. Wins even over
73
+ // `origin`. Naming a remote that does not exist is an error, never a fall-through to a guess.
74
+ // 2. a remote named `origin` — the parity rule: every repo that worked before #301
75
+ // takes byte-for-byte the same path it took then.
76
+ // 3. `remote.pushDefault`, if it names an existing remote.
77
+ // 4. exactly one remote — that one.
78
+ // 5. no remote at all — null (a local-only repo; callers keep their
79
+ // "no remote" behavior).
80
+ // 6. anything else is AMBIGUOUS — refused with the remotes named and the fix. colab
81
+ // never picks one of several remotes by itself.
82
+ // `origin` ranks above `pushDefault` on purpose: pushDefault is a push-only knob used in fork
83
+ // (triangular) setups, and letting it outrank `origin` would silently move where trunk is fetched
84
+ // from and where claims are pushed in a repo that works today. `colab.remote` is the one
85
+ // deliberate way off `origin`. It lives in git config, not project.yml: the remote name belongs to
86
+ // one clone, not to the repo.
87
+ // ---------------------------------------------------------------------------
88
+
89
+ const REMOTE_OVERRIDE_KEY = 'colab.remote';
90
+ const remoteCache = new Map();
91
+
92
+ /** Test hook: forget every cached resolution (a test that adds/renames remotes after resolving). */
93
+ function _resetRemoteCache() { remoteCache.clear(); }
94
+
95
+ function listRemotes(repo) {
96
+ const r = git(['remote'], repo);
97
+ return r.ok && r.stdout ? r.stdout.split('\n').map((x) => x.trim()).filter(Boolean) : [];
98
+ }
99
+
100
+ function configValue(repo, key) {
101
+ const r = git(['config', '--get', key], repo);
102
+ return r.ok && r.stdout ? r.stdout : null;
103
+ }
104
+
105
+ /**
106
+ * How this repo's remote resolves — `{ name, source, remotes }`. NEVER throws (this module's
107
+ * contract: an environment without something is an answer, not an exception); `name` is null for
108
+ * `none`, `ambiguous` and `config-missing`. `source` ∈ config | origin | pushDefault | single |
109
+ * none | ambiguous | config-missing. Cached per resolved repo path for the life of the process —
110
+ * a linked worktree and its main checkout share config, so either path answers the same.
111
+ */
112
+ function remoteInfo(repo) {
113
+ const key = path.resolve(repo || process.cwd());
114
+ if (remoteCache.has(key)) return remoteCache.get(key);
115
+ const remotes = listRemotes(repo);
116
+ const has = (n) => remotes.includes(n);
117
+ let info;
118
+ const override = configValue(repo, REMOTE_OVERRIDE_KEY);
119
+ const pushDefault = configValue(repo, 'remote.pushDefault');
120
+ if (override) info = has(override) ? { name: override, source: 'config' } : { name: null, source: 'config-missing', override };
121
+ else if (has('origin')) info = { name: 'origin', source: 'origin' };
122
+ else if (pushDefault && has(pushDefault)) info = { name: pushDefault, source: 'pushDefault' };
123
+ else if (remotes.length === 1) info = { name: remotes[0], source: 'single' };
124
+ else if (remotes.length === 0) info = { name: null, source: 'none' };
125
+ else info = { name: null, source: 'ambiguous' };
126
+ info.remotes = remotes;
127
+ remoteCache.set(key, info);
128
+ return info;
129
+ }
130
+
131
+ /** The refusal text for an unresolvable remote, or null when it resolves (or there is none). */
132
+ function remoteProblem(info) {
133
+ if (info.source === 'ambiguous') {
134
+ return `this repo has ${info.remotes.length} git remotes (${info.remotes.join(', ')}) and none is named origin — ` +
135
+ `colab will not guess which one to fetch from and push to. Pick one: git config ${REMOTE_OVERRIDE_KEY} <name>`;
136
+ }
137
+ if (info.source === 'config-missing') {
138
+ return `git config ${REMOTE_OVERRIDE_KEY} names "${info.override}", but this repo has no such remote ` +
139
+ `(remotes: ${info.remotes.length ? info.remotes.join(', ') : 'none'}). Fix it: git config ${REMOTE_OVERRIDE_KEY} <name>, ` +
140
+ `or git config --unset ${REMOTE_OVERRIDE_KEY}`;
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /**
146
+ * The remote colab uses in this repo, or null when there is none. THROWS a UserError (loudly,
147
+ * naming the remotes and the fix) when the remotes are ambiguous or the override is broken —
148
+ * the one case this module throws for, because silently guessing a remote is worse than stopping.
149
+ */
150
+ function remoteName(repo) {
151
+ const info = remoteInfo(repo);
152
+ const problem = remoteProblem(info);
153
+ if (problem) {
154
+ const { UserError } = require('./util'); // lazy: util must stay free of a git.js dependency
155
+ throw new UserError(problem);
156
+ }
157
+ return info.name;
158
+ }
159
+
160
+ /**
161
+ * For call sites that used the literal `'origin'` unconditionally: the resolved remote, or the
162
+ * literal `'origin'` when the repo has none — so a local-only repo fails at git exactly as it did
163
+ * before #301 (same command, same error), instead of in some new way. Throws like remoteName.
164
+ */
165
+ function remoteFor(repo) {
166
+ return remoteName(repo) || 'origin';
167
+ }
168
+
169
+ /** URL of the resolved remote, or null (no remote, or unresolvable — never throws). */
170
+ function remoteUrl(repo) {
171
+ const { name } = remoteInfo(repo);
172
+ if (!name) return null;
173
+ const r = git(['remote', 'get-url', name], repo);
174
+ return r.ok && r.stdout ? r.stdout : null;
175
+ }
176
+
177
+ /** Pre-#301 name, kept as an alias: the resolved remote's URL (it was `origin`'s, which is still what an origin repo gets). */
178
+ function originUrl(repo) {
179
+ return remoteUrl(repo);
180
+ }
181
+
182
+ /** Trunk branch name from <remote>/HEAD, best-effort. Never throws: an unresolvable remote reads as `origin`, as before #301. */
183
+ function detectTrunk(repo, remote = remoteInfo(repo).name || 'origin') {
184
+ let r = git(['symbolic-ref', '--short', `refs/remotes/${remote}/HEAD`], repo);
185
+ if (r.ok && r.stdout) return r.stdout.startsWith(`${remote}/`) ? r.stdout.slice(remote.length + 1) : r.stdout;
186
+ r = git(['remote', 'show', remote], repo);
187
+ if (r.ok) {
188
+ const m = r.stdout.match(/HEAD branch:\s*(\S+)/);
189
+ // `(unknown)` is git's placeholder when the remote's HEAD names a branch that does not exist —
190
+ // not a branch. Returned verbatim it became a trunk/owner name (#405).
191
+ if (m && m[1] !== '(unknown)') {
192
+ git(['remote', 'set-head', remote, m[1]], repo); // cache it
193
+ return m[1];
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+
199
+ /**
200
+ * Does a branch name resolve to a ref in this repo — locally, or as origin's copy?
201
+ *
202
+ * The local check alone is not enough: a session on another machine pushed the branch, and a claim
203
+ * naming it is perfectly healthy here. False in this function therefore means "nothing anywhere
204
+ * knows this name", which is the only claim strong enough to refuse a ship over. A falsy branch
205
+ * (null = "no branch") is false without asking git.
206
+ */
207
+ function branchExists(repo, branch, remote = remoteInfo(repo).name || 'origin') {
208
+ if (!branch || typeof branch !== 'string') return false;
209
+ for (const ref of [`refs/heads/${branch}`, `refs/remotes/${remote}/${branch}`]) {
210
+ if (git(['rev-parse', '--verify', '--quiet', ref], repo).ok) return true;
211
+ }
212
+ return false;
213
+ }
214
+
215
+ /**
216
+ * #324: WHERE a branch name resolves — `{localSha, remoteSha}`, each a full sha or null. The answer
217
+ * `branchExists` above deliberately flattens: "exists only as origin's copy" is exactly the shape of
218
+ * another machine's work, which `ship` must not adopt silently. Read it BEFORE anything that runs
219
+ * `git worktree add <dir> <branch>`: git's DWIM checkout silently creates the local ref from the
220
+ * remote one, after which the branch is indistinguishable from one this machine made.
221
+ *
222
+ * #343: "indistinguishable" by refs alone — but not by the branch's reflog. `localFromRemote` is true
223
+ * when the local ref's OLDEST reflog entry says it was created from origin's copy of the SAME name.
224
+ * Measured on git 2.55, one fixture per creation path:
225
+ * git checkout <b> / git switch <b> / git worktree add <dir> <b> (DWIM)
226
+ * → `branch: Created from refs/remotes/origin/<b>`
227
+ * git branch --track <b> origin/<b> / git worktree add -b <b> <dir> origin/<b> / checkout -b <b> origin/<b>
228
+ * → `branch: Created from origin/<b>`
229
+ * git checkout -b <b> → `branch: Created from HEAD` (a local branch)
230
+ * git checkout -b <b> origin/main → `branch: Created from origin/main` (a local branch)
231
+ * The signal is one-directional: it can only turn a "local" reading into "came from origin", never
232
+ * the reverse. Where it is absent it degrades to the pre-#343 reading, silently — the known blind
233
+ * spots are an expired reflog (gc.reflogExpire, 90 days by default), `core.logAllRefUpdates=false`,
234
+ * and a ref created by `git fetch origin <b>:<b>` (reflog `fetch …: storing head`, deliberately not
235
+ * matched — its wording carries the refspec, not a "created from" source).
236
+ */
237
+ function branchRefs(repo, branch, remote = remoteInfo(repo).name || 'origin') {
238
+ if (!branch || typeof branch !== 'string') return { localSha: null, remoteSha: null, localFromRemote: false };
239
+ const at = (ref) => { const r = git(['rev-parse', '--verify', '--quiet', ref], repo); return r.ok && r.stdout ? r.stdout : null; };
240
+ const localSha = at(`refs/heads/${branch}`);
241
+ const remoteSha = at(`refs/remotes/${remote}/${branch}`);
242
+ return { localSha, remoteSha, localFromRemote: localSha ? createdFromRemote(repo, branch, remote) : false };
243
+ }
244
+
245
+ /** #343: is `refs/heads/<branch>`'s oldest reflog entry "Created from <remote>/<branch>"? See branchRefs. */
246
+ function createdFromRemote(repo, branch, remote = remoteInfo(repo).name || 'origin') {
247
+ const r = git(['reflog', 'show', '--format=%gs', `refs/heads/${branch}`, '--'], repo);
248
+ if (!r.ok || !r.stdout) return false;
249
+ const lines = r.stdout.split('\n').filter(Boolean);
250
+ const oldest = lines[lines.length - 1] || '';
251
+ return oldest === `branch: Created from refs/remotes/${remote}/${branch}` || oldest === `branch: Created from ${remote}/${branch}`;
252
+ }
253
+
254
+ /**
255
+ * Authoritative "does this branch name already resolve to a ref" check — for the one caller
256
+ * (`worktree new`, #124) that must refuse rather than silently cut a fresh branch over an
257
+ * existing one's history.
258
+ *
259
+ * `branchExists` above is not enough here: it trusts the LOCAL remote-tracking ref, and the
260
+ * `git fetch origin <base>` `worktree new` runs beforehand only refreshes `base` — never an
261
+ * arbitrary branch name — so a branch pushed from another machine (or by a session whose
262
+ * worktree was already torn down) can be invisible to it. `ls-remote` asks origin directly, no
263
+ * local cache involved, so it is fresh regardless of what has or hasn't been fetched.
264
+ *
265
+ * Local wins when both exist (it is the one a `git worktree add -b` would actually collide
266
+ * with). Returns `{ ref, sha }` (sha short, 7 chars) or `null` when neither resolves.
267
+ */
268
+ function existingBranchRef(repo, branch, remote = remoteFor(repo)) {
269
+ if (!branch || typeof branch !== 'string') return null;
270
+ const local = git(['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], repo);
271
+ if (local.ok && local.stdout) return { ref: `refs/heads/${branch}`, sha: local.stdout.slice(0, 7) };
272
+ const r = git(['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], repo);
273
+ if (r.ok && r.stdout) {
274
+ const sha = r.stdout.split(/\s+/)[0] || '';
275
+ return { ref: `refs/remotes/${remote}/${branch}`, sha: sha.slice(0, 7) };
276
+ }
277
+ return null;
278
+ }
279
+
280
+ /**
281
+ * The git remote a CLAIM is recorded on (#325). Since #301 this is `remoteName` — the same resolver
282
+ * every other remote-touching command uses — so claims live on the remote everything else fetches
283
+ * from. `null` = a repo with no remote at all, where the local record is the whole truth because
284
+ * nothing else could ever share the branch. Throws on ambiguous remotes, like remoteName.
285
+ */
286
+ function claimRemote(repo) {
287
+ return remoteName(repo);
288
+ }
289
+
290
+ /**
291
+ * Every branch head on `remoteName`, asked of the remote directly (`ls-remote --heads`, no fetch, no
292
+ * local cache) — the claim record another machine can read (#325). Unlike `existingBranchRef`, a
293
+ * failed ask is NOT "no branches": it returns `{ ok: false, stderr }` so the caller can refuse
294
+ * (fail closed) instead of reading an unreachable remote as clear ground.
295
+ * `{ ok: true, heads: [{ branch, sha }] }` otherwise, `sha` short (7).
296
+ */
297
+ function remoteHeads(repo, remoteName) {
298
+ const r = git(['ls-remote', '--heads', remoteName], repo, { timeoutMs: 60_000 });
299
+ if (!r.ok) return { ok: false, stderr: r.stderr || (r.timedOut ? 'ls-remote timed out' : `exit ${r.code}`) };
300
+ const heads = [];
301
+ for (const line of String(r.stdout || '').split('\n')) {
302
+ const m = line.match(/^([0-9a-f]{7,})\s+refs\/heads\/(.+)$/);
303
+ if (m) heads.push({ branch: m[2], sha: m[1].slice(0, 7) });
304
+ }
305
+ return { ok: true, heads };
306
+ }
307
+
308
+ /** List worktree paths registered in a repo (porcelain). */
309
+ function worktreeList(repo) {
310
+ const r = git(['worktree', 'list', '--porcelain'], repo);
311
+ if (!r.ok) return [];
312
+ return r.stdout.split('\n')
313
+ .filter((l) => l.startsWith('worktree '))
314
+ .map((l) => l.slice('worktree '.length));
315
+ }
316
+
317
+ /**
318
+ * `git worktree list --porcelain`, parsed per-block instead of flattened — a caller that needs
319
+ * "which branch is checked out at THIS path" (not just "is this branch checked out somewhere")
320
+ * needs the path/branch pairing, which a flat line-filter throws away. Returns
321
+ * `[{path, branch, detached, bare}]`; `branch` is null for a detached or bare entry.
322
+ *
323
+ * Ground truth for what worktrees actually exist, independent of anyone's record of them — see
324
+ * `worktreeList` above for the flat form, kept because `shippedBranches` only ever needed "is this
325
+ * branch checked out anywhere" and a block parse would be pure overhead there.
326
+ */
327
+ function worktreeListDetailed(repo) {
328
+ const r = git(['worktree', 'list', '--porcelain'], repo);
329
+ if (!r.ok) return [];
330
+ const out = [];
331
+ let cur = null;
332
+ for (const line of r.stdout.split('\n')) {
333
+ if (line.startsWith('worktree ')) {
334
+ if (cur) out.push(cur);
335
+ cur = { path: line.slice('worktree '.length), branch: null, detached: false, bare: false };
336
+ } else if (cur && line.startsWith('branch ')) {
337
+ cur.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '');
338
+ } else if (cur && line === 'detached') {
339
+ cur.detached = true;
340
+ } else if (cur && line === 'bare') {
341
+ cur.bare = true;
342
+ }
343
+ }
344
+ if (cur) out.push(cur);
345
+ return out;
346
+ }
347
+
348
+ /**
349
+ * Resolves where `branch` is actually checked out right now, from git's own ground truth —
350
+ * never a caller's own record of it (a `wtPath` field on a session/worktree object), which can
351
+ * be null or stale (the record went missing, or was never written — happens, has multiple real
352
+ * producers) while a live worktree of that branch still exists on disk. `colab ship`'s B0 used
353
+ * to trust `sess.wtPath` alone and, on a stale/missing record, fall through to minting an
354
+ * ADDITIONAL temp checkout of the same branch — which git then refuses ("already checked out
355
+ * at …"), because two checkouts of one branch is something git itself does not allow (#286).
356
+ *
357
+ * Built on `worktreeListDetailed` above rather than re-parsing `--porcelain` output — same
358
+ * ground-truth source already used for `colab worktrees`' reconciliation and the orphan-branch
359
+ * scan, and already covered by its own tests.
360
+ *
361
+ * Returns null when git itself says the branch is not checked out anywhere — the only case in
362
+ * which minting a fresh (ephemeral) checkout is safe.
363
+ */
364
+ function resolveWorktreePathForBranch(repo, branch) {
365
+ const hit = worktreeListDetailed(repo).find((w) => w.branch === branch);
366
+ return hit ? hit.path : null;
367
+ }
368
+
369
+ /**
370
+ * `stderr.split('\n')[0]` on a failed `git worktree add` keeps git's own generic progress line
371
+ * ("Preparing worktree (checking out '<branch>')") and discards the `fatal:` line beneath it —
372
+ * the only line that actually names what went wrong, including (in a checkout-collision) the
373
+ * path of the worktree already holding that branch (#287). Prefer the first `fatal:` line; fall
374
+ * back to the last non-empty line for a failure that doesn't say `fatal:` at all, rather than
375
+ * always the first line, which is the one most likely to be boilerplate progress output.
376
+ */
377
+ function gitFailureLine(stderr) {
378
+ const lines = (stderr || '').split('\n');
379
+ const fatal = lines.find((l) => l.startsWith('fatal:'));
380
+ if (fatal) return fatal;
381
+ const nonEmpty = lines.filter(Boolean);
382
+ return nonEmpty.length ? nonEmpty[nonEmpty.length - 1] : lines[0];
383
+ }
384
+
385
+ /**
386
+ * `git status --porcelain` split into its tracked and untracked halves, or null if git could not
387
+ * answer. Two deliberate choices, both load-bearing for the callers below:
388
+ *
389
+ * - **`-uall`, not the default `-unormal`.** Porcelain normally collapses an untracked directory
390
+ * into a single `?? dir/` line. The callers of `dirtyUntracked` are about to DELETE what they
391
+ * are describing, and `?? tools/lib/` does not tell a human which of their new sources is at
392
+ * stake. Listing them costs a directory walk over non-ignored paths only.
393
+ * - **No `--ignored`, ever.** Ignored files stay invisible here by construction. Build output,
394
+ * `node_modules`, a copied `.env` — those are exactly what a teardown is right to destroy
395
+ * without asking, and a worktree post-create hook legitimately produces them.
396
+ */
397
+ function statusPorcelain(wtPath) {
398
+ const r = git(['status', '--porcelain', '-uall'], wtPath);
399
+ if (!r.ok) return null;
400
+ const lines = r.stdout.split('\n').filter(Boolean);
401
+ return {
402
+ tracked: lines.filter((l) => !l.startsWith('??')),
403
+ untracked: lines.filter((l) => l.startsWith('??')),
404
+ };
405
+ }
406
+
407
+ // All three degrade to '' ("clean") when git itself cannot answer, which for a destructive caller
408
+ // means "proceed". That is deliberate and not a fail-open bug: the case where `git status` fails in
409
+ // a directory that exists is a worktree that is no longer a worktree — the #62 husk, whose whole
410
+ // removal path exists to clean it up. A gate that refused there would make husks unremovable.
411
+
412
+ /** Tracked (non-untracked) uncommitted changes in a worktree, or '' if clean. */
413
+ function dirtyTracked(wtPath) {
414
+ const s = statusPorcelain(wtPath);
415
+ return s ? s.tracked.join('\n') : '';
416
+ }
417
+
418
+ /**
419
+ * Untracked, NON-IGNORED files in a worktree, or '' if none (#86).
420
+ *
421
+ * The companion `dirtyTracked` never had. A file that has never been `git add`ed exists in exactly
422
+ * one place — the working tree — so it is the ONLY category of work a teardown can destroy with
423
+ * nothing to restore from: not the index, not a commit, not the remote. Tracked changes always
424
+ * have at least a committed base to diff against; untracked ones have nothing.
425
+ */
426
+ function dirtyUntracked(wtPath) {
427
+ const s = statusPorcelain(wtPath);
428
+ return s ? s.untracked.join('\n') : '';
429
+ }
430
+
431
+ /** Everything uncommitted: tracked changes AND untracked non-ignored files. '' if the tree is clean. */
432
+ function dirtyAny(wtPath) {
433
+ const s = statusPorcelain(wtPath);
434
+ return s ? [...s.tracked, ...s.untracked].join('\n') : '';
435
+ }
436
+
437
+ // ---- gh ----
438
+
439
+ /**
440
+ * #344: is gh usable — and if not, WHY. `{ ok, reason }`, reason `null` | `'missing'` (no gh binary)
441
+ * | `'no-credential'` (gh is there, but the credential it would actually use does not work). Cached
442
+ * per process.
443
+ *
444
+ * A bare `gh auth status` is the wrong question: it exits 1 when ANY configured account is broken,
445
+ * even when the one gh actually uses is fine (measured: a valid `GH_TOKEN` plus an expired, inactive
446
+ * keyring account → `gh auth status` exit 1 while `gh api user` / `gh run list` work). That read gh
447
+ * as absent for the whole run — ship refused CI, claims went local-only — and flipped whenever the
448
+ * inactive token expired. So: `gh auth status --active` (only the account gh will use; present on
449
+ * gh 2.98, measured — absent on older builds)
450
+ * first, and when that fails — an older gh without the flag, or a genuinely broken active account —
451
+ * the decisive probe is the credential doing real work: `gh api user`.
452
+ */
453
+ let _ghState = null;
454
+ function ghState() {
455
+ if (_ghState) return _ghState;
456
+ if (!run('gh', ['--version']).ok) return (_ghState = { ok: false, reason: 'missing' });
457
+ if (run('gh', ['auth', 'status', '--active']).ok) return (_ghState = { ok: true, reason: null });
458
+ const who = run('gh', ['api', 'user', '-q', '.login']);
459
+ if (who.ok && who.stdout) {
460
+ if (_ghLogin === undefined) _ghLogin = who.stdout;
461
+ return (_ghState = { ok: true, reason: null });
462
+ }
463
+ return (_ghState = { ok: false, reason: 'no-credential' });
464
+ }
465
+
466
+ function ghAvailable() {
467
+ return ghState().ok;
468
+ }
469
+
470
+ /** gh issue edit — returns {ok, stderr}. cwd must be inside the repo so gh resolves the remote. */
471
+ function ghIssueEdit(repo, issueNum, args) {
472
+ return run('gh', ['issue', 'edit', String(issueNum), ...args], { cwd: repo });
473
+ }
474
+
475
+ /** The current gh user's login (`gh api user`), or null if it can't be determined. Cached. */
476
+ let _ghLogin;
477
+ function ghCurrentLogin() {
478
+ if (_ghLogin !== undefined) return _ghLogin;
479
+ const r = run('gh', ['api', 'user', '-q', '.login']);
480
+ _ghLogin = r.ok && r.stdout ? r.stdout : null;
481
+ return _ghLogin;
482
+ }
483
+
484
+ /** Raw `gh api` call — returns {ok, stdout, stderr, code}. cwd must be inside the repo so `{owner}`
485
+ * / `{repo}` placeholders resolve to the right remote. */
486
+ function ghApi(repo, args) {
487
+ return run('gh', ['api', ...args], { cwd: repo });
488
+ }
489
+
490
+ /**
491
+ * True when a gh CLI failure is specifically a GraphQL quota exhaustion, not a REST one (#164).
492
+ * `gh` prefixes every GraphQL-transport error with a literal `GraphQL:` on the first line of
493
+ * stderr (its own reporting convention, not something we control) — so this is the one reliable
494
+ * signal that the failing write went over GraphQL rather than REST. REST and GraphQL are counted
495
+ * as SEPARATE hourly quotas, so this failure says nothing about whether the REST equivalent below
496
+ * can still complete — that is the entire reason a fallback is worth attempting.
497
+ */
498
+ function isGraphqlRateLimit(stderr) {
499
+ const first = String(stderr || '').split('\n')[0] || '';
500
+ return /^GraphQL:/i.test(first) && /rate limit/i.test(first);
501
+ }
502
+
503
+ /**
504
+ * Who holds an issue's tracker claim, read from the issue itself (#363) — never assumed to be the
505
+ * caller. A fleet that works under more than one account (an operator login and an agent login,
506
+ * say) routinely claims under one and releases under the other; a release that only drops `@me`
507
+ * then removes `in-progress` and leaves the claimer assigned — a half-claim by §5's own
508
+ * definition, which nobody starts and nothing repairs.
509
+ *
510
+ * The claimer is the actor of the LATEST `labeled in-progress` event: the claim writes the label
511
+ * and the assignee in one call, by one account, so that actor is the account whose assignee is
512
+ * the claim's other half. The event survives the label's removal, so this also finds the claimer
513
+ * of an issue already reduced to an assignee-only half-claim — the repair case.
514
+ *
515
+ * Both reads are REST (`gh api`), deliberately: release has a REST fallback for a GraphQL-only
516
+ * rate limit (#164), and a lookup that spent GraphQL quota would fail in exactly that case.
517
+ * Returns {assignees, claimer}; either is null when it could not be read — "could not read",
518
+ * never "nobody", the same contract as ghIssueView.
519
+ */
520
+ function ghClaimHolder(repo, issueNum) {
521
+ const a = ghApi(repo, [`repos/{owner}/{repo}/issues/${issueNum}`, '--jq', '.assignees[].login']);
522
+ const assignees = a.ok ? String(a.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean) : null;
523
+ const e = ghApi(repo, [
524
+ '--paginate', `repos/{owner}/{repo}/issues/${issueNum}/events`,
525
+ '--jq', '.[] | select(.event == "labeled" and .label.name == "in-progress") | .actor.login',
526
+ ]);
527
+ const actors = e.ok ? String(e.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean) : [];
528
+ const claimer = actors.length ? actors[actors.length - 1] : null;
529
+ return { assignees, claimer };
530
+ }
531
+
532
+ /**
533
+ * Release an issue's tracker claim — remove the `in-progress` label and the assignee that holds
534
+ * the claim. Primary path is `gh issue edit` (GraphQL, one mutation for both). On a GraphQL-specific
535
+ * rate limit (#164) it retries each half over REST instead, since the two quotas are independent:
536
+ * DELETE /repos/{owner}/{repo}/issues/{n}/labels/in-progress
537
+ * DELETE /repos/{owner}/{repo}/issues/{n}/assignees (body: {assignees:[login,...]})
538
+ * Any other kind of failure (network down, issue not found, ...) is NOT retried — a GraphQL
539
+ * rate limit is the one case where "try a different transport" is actually a different question,
540
+ * not a repeat of the same one.
541
+ *
542
+ * Which assignee (#363): the caller (`@me`, always — unassigning a login that is not assigned is a
543
+ * no-op) AND the claimer read from the issue by `ghClaimHolder`, when that is a different login
544
+ * still assigned. `opts.selfOnly` restricts it to `@me` — for the yield path, where the latest
545
+ * labeler may be the WINNER of the race, whose assignee must survive. A lookup that fails
546
+ * degrades to `@me` alone (the pre-#363 behaviour) and says so in `note`; it never blocks the
547
+ * release.
548
+ *
549
+ * Returns {ok, stderr, code, others, caller, note}: `others` = logins other than the caller that
550
+ * were unassigned (empty in the ordinary one-account case) — a caller prints them, because
551
+ * removing someone else's assignee is a thing a human should see happened.
552
+ */
553
+ function ghIssueRelease(repo, issueNum, opts = {}) {
554
+ const caller = ghCurrentLogin();
555
+ let others = [];
556
+ let note = '';
557
+ if (!opts.selfOnly) {
558
+ const h = ghClaimHolder(repo, issueNum);
559
+ if (h.claimer && h.claimer !== caller && (h.assignees === null || h.assignees.includes(h.claimer))) {
560
+ others = [h.claimer];
561
+ } else if (!h.claimer && h.assignees === null) {
562
+ note = 'could not read who holds the claim — unassigned @me only';
563
+ }
564
+ }
565
+ const r = run('gh', ['issue', 'edit', String(issueNum),
566
+ '--remove-assignee', ['@me', ...others].join(','), '--remove-label', 'in-progress'], { cwd: repo });
567
+ if (r.ok || !isGraphqlRateLimit(r.stderr)) return { ...r, others: r.ok ? others : [], caller, note };
568
+
569
+ const label = ghApi(repo, ['-X', 'DELETE', `repos/{owner}/{repo}/issues/${issueNum}/labels/in-progress`]);
570
+ const logins = [caller, ...others].filter(Boolean);
571
+ const assignee = logins.length
572
+ ? ghApi(repo, ['-X', 'DELETE', `repos/{owner}/{repo}/issues/${issueNum}/assignees`,
573
+ ...logins.flatMap((l) => ['-f', `assignees[]=${l}`])])
574
+ : { ok: false, stderr: 'could not resolve current gh login for assignee removal (gh api user failed)' };
575
+
576
+ const ok = label.ok && assignee.ok;
577
+ const stderr = ok ? '' : [
578
+ !label.ok && `label removal: ${label.stderr.split('\n')[0] || label.code}`,
579
+ !assignee.ok && `assignee removal: ${assignee.stderr.split('\n')[0] || assignee.code}`,
580
+ ].filter(Boolean).join('; ');
581
+ return { ok, stderr, code: ok ? 0 : 1, others: assignee.ok ? others : [], caller, note };
582
+ }
583
+
584
+ /**
585
+ * `gh issue view N --json <fields>` → parsed object, or null on any failure (gh missing,
586
+ * bad repo, network, unparseable). Callers treat null as "couldn't read" — never as "empty".
587
+ */
588
+ function ghIssueView(repo, issueNum, fields) {
589
+ const r = run('gh', ['issue', 'view', String(issueNum), '--json', fields.join(',')], { cwd: repo });
590
+ if (!r.ok) return null;
591
+ try { return JSON.parse(r.stdout); }
592
+ catch (_) { return null; }
593
+ }
594
+
595
+ /**
596
+ * Post a comment on an issue — returns {ok, stderr}. Best-effort at the call sites. Primary path
597
+ * is `gh issue comment` (GraphQL); on a GraphQL-specific rate limit (#164) it retries once over
598
+ * the REST equivalent (`POST /repos/{owner}/{repo}/issues/{n}/comments`) — a separate quota, so a
599
+ * GraphQL exhaustion says nothing about whether this can still land.
600
+ */
601
+ /**
602
+ * #350: the OPEN pull request whose head is `branch`, with its reviews, or null (none open, or the
603
+ * read failed — `{ error }` distinguishes the two). One call answers both "is there a PR?" and "has
604
+ * someone approved it?", so the core-path pause costs one read on the resume path.
605
+ */
606
+ function ghPrForBranch(repo, branch) {
607
+ const r = run('gh', ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number,url,state,author,headRefOid,reviews'], { cwd: repo });
608
+ if (!r.ok) return { error: (r.stderr || '').split('\n')[0] || `gh pr list exited ${r.code}` };
609
+ try {
610
+ const list = JSON.parse(r.stdout || '[]');
611
+ return { pr: Array.isArray(list) && list.length ? list[0] : null };
612
+ } catch (_) { return { error: 'gh pr list returned unparseable JSON' }; }
613
+ }
614
+
615
+ /**
616
+ * #367: the forge's visibility for this repo — "PUBLIC" | "PRIVATE" | "INTERNAL" — or null when it
617
+ * could not be read (no gh, no GitHub remote, offline). Null is "could not read", never "private":
618
+ * tools/lib/machine-trailer.js fails closed on it.
619
+ */
620
+ function ghRepoVisibility(repo) {
621
+ const r = run('gh', ['repo', 'view', '--json', 'visibility', '-q', '.visibility'], { cwd: repo });
622
+ if (!r.ok) return null;
623
+ const v = (r.stdout || '').trim().toUpperCase();
624
+ return /^[A-Z]+$/.test(v) ? v : null;
625
+ }
626
+
627
+ /** #350: open a PR `head` → `base`. Returns {ok, url, stderr}; `url` is gh's printed PR URL. */
628
+ function ghPrCreate(repo, { base, head, title, body }) {
629
+ const r = run('gh', ['pr', 'create', '--base', base, '--head', head, '--title', title, '--body', body], { cwd: repo });
630
+ const url = (r.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean).pop() || null;
631
+ return { ok: r.ok, url, stderr: r.stderr };
632
+ }
633
+
634
+ /** #350: close a PR whose work landed by squash elsewhere, with a comment saying where. */
635
+ function ghPrClose(repo, num, comment) {
636
+ return run('gh', ['pr', 'close', String(num), '--comment', comment], { cwd: repo });
637
+ }
638
+
639
+ function ghIssueComment(repo, issueNum, body) {
640
+ const r = run('gh', ['issue', 'comment', String(issueNum), '--body', body], { cwd: repo });
641
+ if (r.ok || !isGraphqlRateLimit(r.stderr)) return r;
642
+ return ghApi(repo, ['-X', 'POST', `repos/{owner}/{repo}/issues/${issueNum}/comments`, '-f', `body=${body}`]);
643
+ }
644
+
645
+ /**
646
+ * #357: the created-at timestamps of every `labeled` event for `label` on one issue (issue
647
+ * events API, paginated), oldest-first — or null when the read failed. Null is "could not read",
648
+ * never "no events": tools/lib/decision-record.js pairVerdict keeps an unread timeline
649
+ * UNDETERMINED (surfaced as pending) rather than guessing.
650
+ */
651
+ function ghIssueLabelEvents(repo, issueNum, label) {
652
+ const r = ghApi(repo, [
653
+ '--paginate', `repos/{owner}/{repo}/issues/${issueNum}/events`,
654
+ '--jq', `.[] | select(.event == "labeled" and .label.name == ${JSON.stringify(label)}) | .created_at`,
655
+ ]);
656
+ if (!r.ok) return null;
657
+ return String(r.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean);
658
+ }
659
+
660
+ /**
661
+ * #407: the actor login of every `labeled` event for `label` on one issue, oldest-first — or null
662
+ * when the read failed ("could not read", never "nobody applied it"). tools/lib/trust-humans.js
663
+ * labelApplierIsHuman reads the LAST one. Only called when a repo declares trust-humans.
664
+ */
665
+ function ghIssueLabelActors(repo, issueNum, label) {
666
+ const r = ghApi(repo, [
667
+ '--paginate', `repos/{owner}/{repo}/issues/${issueNum}/events`,
668
+ '--jq', `.[] | select(.event == "labeled" and .label.name == ${JSON.stringify(label)}) | .actor.login`,
669
+ ]);
670
+ if (!r.ok) return null;
671
+ return String(r.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean);
672
+ }
673
+
674
+ /**
675
+ * The label names defined on a repo's tracker (`gh label list`), or null on any failure (gh
676
+ * missing, no remote, network). Null means "could not read" — never "empty set", the same
677
+ * contract as ghIssueView: a caller must not read absence as proof a label is missing.
678
+ */
679
+ function ghListLabels(repo) {
680
+ const r = run('gh', ['label', 'list', '--limit', '500', '--json', 'name', '-q', '.[].name'], { cwd: repo });
681
+ if (!r.ok) return null;
682
+ return r.stdout.split('\n').map((s) => s.trim()).filter(Boolean);
683
+ }
684
+
685
+ /**
686
+ * `gh issue list --label <name> --state <state>` → array of parsed objects (the requested JSON
687
+ * fields), or null on failure (gh missing, no remote, network). Null means "could not read" —
688
+ * the same contract as ghIssueView; a caller must not read a failed call as "no issues".
689
+ */
690
+ function ghIssueListByLabel(repo, label, state, fields) {
691
+ const r = run('gh', ['issue', 'list', '--label', label, '--state', state,
692
+ '--json', fields.join(','), '--limit', '200'], { cwd: repo });
693
+ if (!r.ok) return null;
694
+ try { return JSON.parse(r.stdout); }
695
+ catch (_) { return null; }
696
+ }
697
+
698
+ /**
699
+ * `gh label delete <name> --yes` — returns {ok, stderr}. Deletes the LABEL OBJECT from the
700
+ * repo's tracker, not one issue's use of it — every issue that carried it loses it. Callers
701
+ * that mean "remove this label from one issue" want ghIssueEdit(..., ['--remove-label', name])
702
+ * instead; this is only for tearing down a spent `group:<key>` label (CONVENTIONS.md §5).
703
+ */
704
+ function ghLabelDelete(repo, name) {
705
+ return run('gh', ['label', 'delete', name, '--yes'], { cwd: repo });
706
+ }
707
+
708
+ /**
709
+ * `gh label create <name> --color <color> --description <description>`, or the raw `run()`
710
+ * result on failure (the label already exists, no auth, rate limit) — the caller (`colab labels
711
+ * --ensure`, #206) decides what a failure means; this is a thin wrapper, same posture as
712
+ * ghLabelDelete just above. No `--force`: overwriting an existing label's color/description is a
713
+ * different, more destructive act than provisioning a MISSING one, and `--ensure`'s whole contract
714
+ * is "create what's absent, never touch what's there" — the caller checks presence first via
715
+ * ghListLabels and only calls this for a name confirmed missing.
716
+ */
717
+ function ghLabelCreate(repo, name, color, description) {
718
+ return run('gh', ['label', 'create', name, '--color', color, '--description', description], { cwd: repo });
719
+ }
720
+
721
+ /**
722
+ * `gh label list` WITH descriptions → [{ name, description }], or null on failure — the same
723
+ * null-means-could-not-read contract as ghListLabels (which stays names-only for its many
724
+ * callers). Only `colab labels --ensure` needs the text, to find a convention label whose
725
+ * description has drifted from the handbook's (#364).
726
+ */
727
+ function ghListLabelsDetailed(repo) {
728
+ const r = run('gh', ['label', 'list', '--limit', '500', '--json', 'name,description'], { cwd: repo });
729
+ if (!r.ok) return null;
730
+ try {
731
+ const rows = JSON.parse(r.stdout);
732
+ if (!Array.isArray(rows)) return null;
733
+ return rows.map((l) => ({ name: String(l.name), description: typeof l.description === 'string' ? l.description : '' }));
734
+ } catch (_) { return null; }
735
+ }
736
+
737
+ /**
738
+ * `gh label edit <name> --description <text>` — returns {ok, stderr}. Rewrites ONE label's
739
+ * description on the tracker; colour is deliberately never passed (#364 out of scope). Called
740
+ * only by `colab labels --ensure --refresh-descriptions`, for a name ghListLabelsDetailed just
741
+ * read with a differing description.
742
+ */
743
+ function ghLabelEditDescription(repo, name, description) {
744
+ return run('gh', ['label', 'edit', name, '--description', description], { cwd: repo });
745
+ }
746
+
747
+ /**
748
+ * CI verdict for a branch, judged by SHA rather than by recency (#92).
749
+ *
750
+ * The naive "read the newest run" reading breaks under the repo's own
751
+ * `concurrency: { cancel-in-progress: true }`: two runs can race on one push, one gets cancelled by
752
+ * design, and if THAT one happens to land last, the gate reports red while an identical run on the
753
+ * exact same commit already passed. Nothing inside `colab ship` can clear that — the branch that
754
+ * would produce a newer run is the one the gate is blocking — so it deadlocked every queued ship
755
+ * until a human re-ran the cancelled workflow by hand.
756
+ *
757
+ * Ask the right question instead: does a completed, successful run exist for `branch`'s CURRENT
758
+ * remote head? `git ls-remote` reads that head without touching local refs — this may run before
759
+ * any fetch, mid-precondition. `-L limit` widens the window past "the latest row" because the
760
+ * duplicate this exists for can be two runs deep.
761
+ *
762
+ * Returns { status, conclusion, sha, createdAt, databaseId, runCount }:
763
+ * - EVERY run at the head sha finished, and one succeeded → {status:'completed', conclusion:'success', sha}
764
+ * - the head sha has run(s) and no green verdict is owed → {status, conclusion} of the most
765
+ * informative one (a still-running row over a finished-but-failed/cancelled one), sha set.
766
+ * "No green verdict owed" covers both a sha where nothing succeeded AND a sha where something
767
+ * did but a sibling has not finished yet (#307) — the latter reads as still-running, not green.
768
+ * - the head sha has no run in the recent window → {status:'none', conclusion:null, sha}
769
+ * (still not green — this is also how a billing-style fail-to-start reads: no run was ever
770
+ * created for the commit that would need one)
771
+ * - the branch does not exist on the remote (#301: the resolved one, `origin` in an origin repo), or `git`/`gh` failed → null
772
+ * `runCount` (#176) is additive on every non-null branch — the number of workflow rows found at
773
+ * that sha (0 for the 'none' case) — so a caller can report a verdict that names its own sample
774
+ * size instead of a bare singular that hides how many workflows were actually consulted.
775
+ *
776
+ * A cancelled sibling of a passing run on the SAME sha is not evidence of anything — it is simply
777
+ * not read, because the passing run for that sha is what answers the question. Any OTHER completed
778
+ * conclusion sitting next to it is a different matter: `forSha` holds one row per workflow, and
779
+ * green requires ALL of them to have succeeded (cancelled excepted), not merely one having
780
+ * succeeded (#146/#162/#165) — checked BEFORE the success check below, so a `failure`, `timed_out`,
781
+ * `action_required`, `startup_failure`, or any other not-success completed conclusion is never
782
+ * masked by a passing sibling on the same sha. This is deliberately an ALLOWLIST (only `success` and
783
+ * `cancelled` are not-bad) rather than a denylist of conclusion values as they get discovered —
784
+ * #146 covered `failure` alone and #165 was filed the moment a second denylist entry was on the
785
+ * table; inverting the quantifier once closes the whole family instead of chasing it value by value.
786
+ *
787
+ * That ALL-quantifier binds `status` exactly as it binds `conclusion` (#307), and for one reason:
788
+ * a sibling that has not FINISHED has not passed — it can still fail. Applying the quantifier to
789
+ * only one of the two fields made the same workflow gating when red and invisible when merely
790
+ * unfinished, so a repo whose fast workflows (build, lint) finish ahead of its slow one (a
791
+ * self-hosted test suite) read fully green for as long as the gap between them — tens of minutes
792
+ * on the measured repo, with `colab ship`'s autonomy path trusting exactly this verdict. The
793
+ * not-yet-finished sha therefore falls through to the still-running branch below, which is the
794
+ * state `classifyCiRun` already knows how to handle: SELF_CLEARING (retry later), or HUMAN_GATED
795
+ * when tools/lib/ci-verdict.js finds the run WEDGED rather than merely slow. Nothing here waits or
796
+ * polls — it reports what is true at read time and lets the caller decide.
797
+ */
798
+ function ghRunForSha(repo, branch, limit = 10, remote = remoteInfo(repo).name || 'origin') {
799
+ const head = run('git', ['ls-remote', remote, `refs/heads/${branch}`], { cwd: repo });
800
+ if (!head.ok) return null;
801
+ const sha = (head.stdout.split('\n')[0] || '').split('\t')[0].trim();
802
+ if (!sha) return null; // branch does not exist on the remote
803
+ return ghRunForCommit(repo, branch, sha, limit);
804
+ }
805
+
806
+ /**
807
+ * The same per-sha verdict `ghRunForSha` computes for a branch's CURRENT remote head, generalized
808
+ * to ANY sha reachable through `branch`'s workflow history (#293). `ghRunForSha` resolves its own
809
+ * sha via `git ls-remote` — fine for "is this branch's head green", useless for "was the commit
810
+ * this branch was CUT FROM green", which is almost never any branch's current head. Split out so
811
+ * both callers share one allowlist rule (only `success`/`cancelled` are not-bad) rather than
812
+ * silently drifting apart the way `shipCiCheck` and `ci-grant`'s red check once did (#155's frame).
813
+ *
814
+ * `branch` narrows the `gh run list` query exactly as it does in `ghRunForSha` (workflow runs list
815
+ * by branch, not by sha) — pass the branch whose history `sha` lives on. For a base-sha check that
816
+ * is almost always trunk, since the sha in question is the merge-base a feature branch was cut from.
817
+ *
818
+ * Returns the identical `{status, conclusion, sha, createdAt, databaseId, runCount}` shape as
819
+ * `ghRunForSha` (see its doc comment for what each state means), or null on a `gh`/parse failure or
820
+ * a missing `sha`. Never resolves `sha` itself — a caller with no sha to ask about has nothing to
821
+ * pass here, unlike `ghRunForSha`'s branch-name convenience.
822
+ */
823
+ /**
824
+ * EVERY workflow run at one sha — the raw row list `ghRunForCommit` picks its single verdict from
825
+ * (#321). Same query, same `--json` field set, same filter; split out so both share one filter
826
+ * rather than drifting apart the way `shipCiCheck` and `ci-grant`'s red check once did.
827
+ *
828
+ * Returns the (possibly empty) array of rows at `sha`, or `null` on a `gh`/parse failure or a
829
+ * missing `sha` — `null` is "the read failed", never "no runs", exactly as it is for the singular
830
+ * function below.
831
+ *
832
+ * WHY A CALLER WOULD WANT ALL OF THEM. `ghRunForCommit` answers "is this sha green", for which one
833
+ * picked row is the right answer. It is the WRONG answer for "which jobs are red at this sha": a
834
+ * sha can carry several workflow runs, so building a red-job set from the one picked row could
835
+ * miss a second failing workflow entirely. tools/lib/ci-cure.js's cure rule — condition 2b (#297)
836
+ * and the #321 carve-out — needs the full set for exactly that reason, on both the red sha and the
837
+ * branch head.
838
+ */
839
+ function ghRunsForCommit(repo, branch, sha, limit = 10) {
840
+ if (!sha) return null;
841
+
842
+ // createdAt + databaseId are additive (#155): a NON-completed pick needs both to let a caller
843
+ // judge whether it is merely slow or structurally WEDGED (tools/lib/ci-verdict.js) — createdAt for
844
+ // the age backstop, databaseId to look up its job count (ghRunJobCount, below — a second call, made
845
+ // lazily by the caller, never here: an ordinary green check must not pay for a read it never needs).
846
+ const r = run('gh', ['run', 'list', '--branch', branch, '-L', String(limit),
847
+ // workflowName is additive (#338): `colab release cut`'s full-suite condition groups the rows by
848
+ // workflow — a workflow whose only run at the sha was cancelled never ran its suite.
849
+ '--json', 'headSha,status,conclusion,createdAt,databaseId,workflowName'], { cwd: repo });
850
+ if (!r.ok) return null;
851
+ let runs;
852
+ try { runs = JSON.parse(r.stdout); } catch (_) { return null; }
853
+ if (!Array.isArray(runs)) return null;
854
+ const forSha = runs.filter((x) => x && x.headSha === sha);
855
+ // #413: an empty filter over a sha that HAS a green run was measured intermittently and never
856
+ // reproduced. Opt-in trace of what the read actually returned, so the next occurrence says
857
+ // whether gh answered nothing, answered other shas, or failed in a way that parsed as [].
858
+ if (forSha.length === 0 && process.env.COLAB_DEBUG_CI) {
859
+ const heads = runs.slice(0, 5).map((x) => (x && x.headSha ? String(x.headSha).slice(0, 7) : '?')).join(',');
860
+ process.stderr.write(`colab debug-ci: gh run list --branch ${branch} -L ${limit} → ok=${r.ok} rows=${runs.length} ` +
861
+ `none at ${String(sha).slice(0, 7)} (first heads: ${heads || '-'})\n`);
862
+ }
863
+ return forSha;
864
+ }
865
+
866
+ /**
867
+ * Every run on `ref` at `sha`, WITH its `attempt` (#373). A sibling of ghRunsForCommit, not a change
868
+ * to its field list: batch landing needs the attempt number to enforce "re-run a red:infra ONCE", and
869
+ * nothing else reads it. Null on a gh/parse failure or a missing sha — never "no runs".
870
+ */
871
+ function ghRunsForRef(repo, ref, sha, limit = 20) {
872
+ if (!sha) return null;
873
+ const r = run('gh', ['run', 'list', '--branch', ref, '-L', String(limit),
874
+ '--json', 'headSha,status,conclusion,createdAt,databaseId,workflowName,attempt'], { cwd: repo });
875
+ if (!r.ok) return null;
876
+ let runs;
877
+ try { runs = JSON.parse(r.stdout); } catch (_) { return null; }
878
+ if (!Array.isArray(runs)) return null;
879
+ return runs.filter((x) => x && x.headSha === sha);
880
+ }
881
+
882
+ function ghRunForCommit(repo, branch, sha, limit = 10) {
883
+ return summarizeRunsForCommit(ghRunsForCommit(repo, branch, sha, limit), sha);
884
+ }
885
+
886
+ /**
887
+ * Every run at `sha` read by commit, not by branch recency (#339): `colab release finalize` checks
888
+ * a candidate that may be days and many trunk runs old, which a `--branch main -L 10` window no
889
+ * longer reaches. Same row shape as ghRunsForCommit; null on failure.
890
+ */
891
+ function ghRunsAtCommit(repo, sha, limit = 100) {
892
+ if (!sha) return null;
893
+ const r = run('gh', ['run', 'list', '--commit', sha, '-L', String(limit),
894
+ '--json', 'headSha,status,conclusion,createdAt,databaseId,workflowName,event'], { cwd: repo });
895
+ if (!r.ok) return null;
896
+ let runs;
897
+ try { runs = JSON.parse(r.stdout); } catch (_) { return null; }
898
+ if (!Array.isArray(runs)) return null;
899
+ return runs.filter((x) => x && x.headSha === sha);
900
+ }
901
+
902
+ /**
903
+ * ghRunForCommit's verdict over a BY-COMMIT read (#413) — every run at `sha` whatever ref it ran
904
+ * on, instead of `--branch <ref> -L N`. The second opinion `colab ship` asks for before it calls an
905
+ * empty trunk read `none`: the branch-filtered list was measured returning nothing for a trunk sha
906
+ * whose green run existed, and clearing on its own a minute later. Null on failure, as elsewhere.
907
+ */
908
+ function ghRunForCommitAnyRef(repo, sha, limit = 50) {
909
+ return summarizeRunsForCommit(ghRunsAtCommit(repo, sha, limit), sha);
910
+ }
911
+
912
+ /**
913
+ * Committer time of `sha` in epoch ms, or null when the object is not local or git failed (#413).
914
+ * The committer time of a trunk squash is the moment it was merged, so this is how young a trunk
915
+ * sha is — the window in which "no run yet" is the ordinary state, not a missing workflow.
916
+ */
917
+ function commitTimeMs(repo, sha) {
918
+ if (!sha) return null;
919
+ const r = run('git', ['show', '-s', '--format=%ct', sha], { cwd: repo });
920
+ if (!r.ok) return null;
921
+ const n = Number(r.stdout.trim());
922
+ return Number.isFinite(n) && n > 0 ? n * 1000 : null;
923
+ }
924
+
925
+ /**
926
+ * Runs on `branch` created on or after `sinceDay` (YYYY-MM-DD; a caller filters the exact instant
927
+ * locally) — #339's trunk-green-throughout read. Returns { runs, truncated } or null on failure;
928
+ * `truncated` is true when the read filled its limit, which a caller must treat as unread.
929
+ */
930
+ function ghRunsSince(repo, branch, sinceDay, limit = 1000) {
931
+ const r = run('gh', ['run', 'list', '--branch', branch, '--created', `>=${sinceDay}`, '-L', String(limit),
932
+ '--json', 'headSha,status,conclusion,createdAt,databaseId,workflowName,event'], { cwd: repo });
933
+ if (!r.ok) return null;
934
+ let runs;
935
+ try { runs = JSON.parse(r.stdout); } catch (_) { return null; }
936
+ if (!Array.isArray(runs)) return null;
937
+ return { runs, truncated: runs.length >= limit };
938
+ }
939
+
940
+ /** ghRunForCommit's pick, over rows already read (null in -> null out). */
941
+ function summarizeRunsForCommit(forSha, sha) {
942
+ if (forSha === null) return null;
943
+ if (forSha.length === 0) return { status: 'none', conclusion: null, sha, createdAt: null, databaseId: null, runCount: 0 };
944
+
945
+ // runCount (#176) is additive: how many sibling workflow rows exist at this sha, so a caller can
946
+ // report "N runs at <sha>: all success" instead of a singular verdict that hides how many
947
+ // workflows actually agreed. It is the row count BEFORE any of the picks below, not "how many
948
+ // succeeded" — the picked row already tells the caller the conclusion; this tells it the sample size.
949
+ const runCount = forSha.length;
950
+
951
+ // A completed sibling whose conclusion is anything but success or cancelled makes the sha
952
+ // not-green, regardless of any sibling that succeeded — checked BEFORE the success check below,
953
+ // so it is never masked by a passing one on the same sha.
954
+ const notGreen = forSha.find(
955
+ (x) => x.status === 'completed' && x.conclusion !== 'success' && x.conclusion !== 'cancelled',
956
+ );
957
+ if (notGreen) return { status: 'completed', conclusion: notGreen.conclusion, sha, createdAt: notGreen.createdAt || null, databaseId: notGreen.databaseId || null, runCount };
958
+
959
+ // A green verdict is owed only when EVERY sibling at this sha has finished (#307). A row that is
960
+ // still queued/in_progress has not passed — it has not run — so picking the first completed
961
+ // success here would stamp `runCount` (the FULL sibling count) onto a verdict that inspected one
962
+ // row. Same all-quantifier as `notGreen` above, on `status` instead of `conclusion`; when it does
963
+ // not hold, control reaches the still-running pick below.
964
+ const allFinished = forSha.every((x) => x.status === 'completed');
965
+ const success = allFinished ? forSha.find((x) => x.conclusion === 'success') : null;
966
+ if (success) return { status: 'completed', conclusion: 'success', sha, createdAt: success.createdAt || null, databaseId: success.databaseId || null, runCount };
967
+
968
+ // No green verdict is owed for this sha — either nothing succeeded, or something did while a
969
+ // sibling is still unfinished (#307). Report the most informative row: a run still in flight (the
970
+ // sha may yet go green) over a finished-but-not-successful one (gh returns newest-first, so
971
+ // forSha[0] is the newest remaining row either way).
972
+ const pending = forSha.find((x) => x.status !== 'completed');
973
+ const pick = pending || forSha[0];
974
+ return { status: pick.status, conclusion: pick.conclusion || null, sha, createdAt: pick.createdAt || null, databaseId: pick.databaseId || null, runCount };
975
+ }
976
+
977
+ /**
978
+ * Job count for one workflow run (#155) — how many jobs GitHub has attached to it. A queued run
979
+ * with ZERO jobs has not been picked up by any runner: the measured shape of a billing lockout or a
980
+ * dead runner pool, and the PRIMARY signal tools/lib/ci-verdict.js uses to call a non-completed run
981
+ * WEDGED rather than merely slow. Deliberately a separate call from `ghRunForSha` (never folded into
982
+ * its `--json` field list): job counts require `gh run view`, one call per run, and the ordinary
983
+ * green-trunk ship makes zero of these — callers fetch it lazily, only for a run that is already
984
+ * non-completed and therefore a wedge candidate.
985
+ *
986
+ * Returns the job count, or null if it could not be read (gh failure, run gone) — null must NOT be
987
+ * read as zero; a caller that cannot measure this falls back to the age backstop alone.
988
+ */
989
+ function ghRunJobCount(repo, runDatabaseId) {
990
+ if (runDatabaseId === null || runDatabaseId === undefined) return null;
991
+ const r = run('gh', ['run', 'view', String(runDatabaseId), '--json', 'jobs', '-q', '.jobs | length'], { cwd: repo });
992
+ if (!r.ok) return null;
993
+ const n = Number(r.stdout);
994
+ return Number.isFinite(n) ? n : null;
995
+ }
996
+
997
+ /**
998
+ * The JOBS of one workflow run, with their steps (#321) — `[{name, status, conclusion, startedAt,
999
+ * completedAt, steps: [{name, status, conclusion}]}]`, or `null` if it could not be read (gh
1000
+ * failure, run gone, unparseable body). `null` must NOT be read as "no jobs"; every consumer of
1001
+ * this fails closed on it.
1002
+ *
1003
+ * A SIBLING of `ghRunJobCount` above, deliberately not a refactor of it: that function sits on the
1004
+ * wedge-detection hot path, and rewriting it as `ghRunJobs(...).length` would be churn with real
1005
+ * regression surface for no gain here.
1006
+ *
1007
+ * Costs one `gh run view` per run, so callers fetch it LAZILY — tools/lib/ci-cure.js's cure rule
1008
+ * (condition 2b, #297, and the #321 carve-out) is the only caller today, and `colab ship` reaches
1009
+ * it only for a branch that is already blocked by a red trunk and has passed containment and a
1010
+ * green run of its own. Every other ship path makes zero of these calls.
1011
+ *
1012
+ * Step-level detail is the whole point: GitHub reports a job whose steps were all SKIPPED as
1013
+ * `conclusion: success`, so run- and job-level conclusions are blind to exactly the fast-exit the
1014
+ * carve-out has to catch.
1015
+ */
1016
+ function ghRunJobs(repo, runDatabaseId) {
1017
+ if (runDatabaseId === null || runDatabaseId === undefined) return null;
1018
+ const r = run('gh', ['run', 'view', String(runDatabaseId), '--json', 'jobs'], { cwd: repo });
1019
+ if (!r.ok) return null;
1020
+ let parsed;
1021
+ try { parsed = JSON.parse(r.stdout); } catch (_) { return null; }
1022
+ if (!parsed || !Array.isArray(parsed.jobs)) return null;
1023
+ return parsed.jobs.map((j) => ({
1024
+ name: j && j.name,
1025
+ status: j && j.status,
1026
+ conclusion: j && j.conclusion,
1027
+ startedAt: (j && j.startedAt) || null,
1028
+ completedAt: (j && j.completedAt) || null,
1029
+ steps: j && Array.isArray(j.steps)
1030
+ ? j.steps.map((s) => ({ name: s && s.name, status: s && s.status, conclusion: s && s.conclusion }))
1031
+ : null,
1032
+ }));
1033
+ }
1034
+
1035
+ /**
1036
+ * Issues claimed by the current gh user in a repo = assigned to @me AND labeled in-progress
1037
+ * (that pairing is exactly what `colab claim` writes). Returns array of numbers, or null on failure.
1038
+ */
1039
+ function ghAssignedIssues(repo) {
1040
+ const r = run('gh', ['issue', 'list', '--assignee', '@me', '--label', 'in-progress', '--state', 'open',
1041
+ '--json', 'number', '--limit', '200'], { cwd: repo });
1042
+ if (!r.ok) return null;
1043
+ try { return JSON.parse(r.stdout).map((o) => o.number); }
1044
+ catch (_) { return null; }
1045
+ }
1046
+
1047
+ module.exports = {
1048
+ run, git, repoRoot, mainRepoRoot, originUrl, remoteInfo, remoteName, remoteFor, remoteUrl, remoteProblem, _resetRemoteCache,
1049
+ detectTrunk, branchExists, branchRefs, existingBranchRef,
1050
+ claimRemote, remoteHeads,
1051
+ worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1052
+ dirtyTracked, dirtyUntracked, dirtyAny,
1053
+ ghAvailable, ghState, ghIssueEdit, ghListLabels, ghAssignedIssues,
1054
+ ghCurrentLogin, ghIssueView, ghIssueComment, ghRunForSha, ghRunForCommit, ghRunsForCommit, ghRunsForRef, ghRunsAtCommit, ghRunForCommitAnyRef, commitTimeMs, ghRunsSince, summarizeRunsForCommit,
1055
+ ghRunJobCount, ghRunJobs,
1056
+ ghIssueListByLabel, ghLabelDelete, ghLabelCreate, ghListLabelsDetailed, ghLabelEditDescription,
1057
+ ghApi, isGraphqlRateLimit, ghIssueRelease, ghClaimHolder, ghIssueLabelEvents, ghIssueLabelActors,
1058
+ ghPrForBranch, ghPrCreate, ghPrClose, ghRepoVisibility,
1059
+ };