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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +2 -2
  2. package/README.vi.md +2 -2
  3. package/audit/audit.mjs +218 -53
  4. package/package.json +1 -1
  5. package/templates/README.md +18 -3
  6. package/templates/ci-laravel.yml +360 -40
  7. package/templates/ci-node.yml +491 -35
  8. package/templates/ci-python.yml +301 -32
  9. package/templates/deploy-container-run.mjs +17 -3
  10. package/templates/deploy-xserver.yml +12 -0
  11. package/templates/instruction-files.yml +16 -0
  12. package/templates/pre-commit-instruction-files +55 -0
  13. package/templates/release-auto.yml +16 -3
  14. package/tools/colab +884 -98
  15. package/tools/lib/adopt.js +1 -1
  16. package/tools/lib/audit-cache.js +277 -0
  17. package/tools/lib/batch-stats.js +66 -43
  18. package/tools/lib/ci-cure.js +10 -1
  19. package/tools/lib/claim-comments.js +3 -2
  20. package/tools/lib/codec/decision.d.ts +7 -0
  21. package/tools/lib/codec/decision.js +54 -0
  22. package/tools/lib/codec/hold.d.ts +8 -1
  23. package/tools/lib/codec/hold.js +42 -8
  24. package/tools/lib/codec/release.js +6 -3
  25. package/tools/lib/codec/samples.json +45 -0
  26. package/tools/lib/config-set.js +4 -3
  27. package/tools/lib/cure-diff.js +27 -1
  28. package/tools/lib/decision-record.js +42 -0
  29. package/tools/lib/docs-only.js +47 -0
  30. package/tools/lib/git.js +57 -8
  31. package/tools/lib/grant-policy.js +133 -0
  32. package/tools/lib/instruction-file.js +75 -0
  33. package/tools/lib/instruction-gate.js +179 -0
  34. package/tools/lib/landed-prs.js +58 -0
  35. package/tools/lib/migration-grant.js +29 -5
  36. package/tools/lib/owner-policy.js +110 -0
  37. package/tools/lib/release-cut.js +127 -10
  38. package/tools/lib/release-finalize.js +66 -5
  39. package/tools/lib/ship-batch.js +188 -14
  40. package/tools/lib/ship-handoff.js +212 -0
  41. package/tools/lib/stamp.js +6 -2
  42. package/tools/lib/template-trunk.js +80 -0
  43. package/tools/lib/tree-green.js +21 -4
  44. package/tools/lib/workflow-triggers.js +57 -0
@@ -3,7 +3,7 @@
3
3
  * CODEC (#498, epic #496): the HOLD wire format — the two-line comment that parks an issue
4
4
  * (CONVENTIONS.md §5, *Holds*):
5
5
  *
6
- * Hold: <label> — owner: <who clears it> — wake: <condition>[, <condition>…]
6
+ * Hold: <label> — owner: <who clears it>[ — shape: ask|task|wait] — wake: <condition>[, <condition>…]
7
7
  * Because: <what is left>
8
8
  *
9
9
  * — and the closed `wake:` vocabulary that line's last field is drawn from (#382). Pure and
@@ -114,17 +114,47 @@ function parseQualifiedIssueRef(arg) {
114
114
 
115
115
  // ── the Hold: / Because: lines ───────────────────────────────────────────────────────────────
116
116
 
117
- const HOLD_RE = /^Hold: (\S+) — owner: (.+?) — wake: (.+)$/;
117
+ // `shape:` (#569) sits BETWEEN owner and wake on purpose. An older reader's pattern is
118
+ // `owner: (.+?) — wake: (.+)$`: placed there, the field folds into that reader's owner text and
119
+ // its wake still parses whole. Placed after wake: it would corrupt the wake, and the older reader
120
+ // would report a perfectly good hold as a stall. Never move it.
121
+ const HOLD_RE = /^Hold: (\S+) — owner: (.+?)(?: — shape: (\S+))? — wake: (.+)$/;
118
122
  const BECAUSE_RE = /^Because: (.*)$/;
119
123
 
124
+ /**
125
+ * What the owner is being asked for (#569) — closed, read by equality:
126
+ * ask — a choice between ways forward. Posted as a structured ask (`needs-decision` + a
127
+ * `decision:options` block with a recommended default), never as a bare hold.
128
+ * task — an act only a person can perform: verify by hand, run a privileged script, sign,
129
+ * supply a credential.
130
+ * wait — on a third party, another issue, a ref or a date.
131
+ */
132
+ const HOLD_SHAPES = Object.freeze(['ask', 'task', 'wait']);
133
+
134
+ /**
135
+ * The shape a reader acts on: the declared `shape:` when it is in the closed set, otherwise the
136
+ * inference that predates the field — a `ruling` anywhere in the wake reads as `ask`, anything
137
+ * else as `wait`. `declared` says which. An unknown declared value is not trusted (`invalid` names
138
+ * it) and falls back to the inference, so a typo never silently re-routes a hold.
139
+ * @returns {{shape:'ask'|'task'|'wait', declared:boolean, invalid:string|null}}
140
+ */
141
+ function holdShape(decoded) {
142
+ const d = decoded || {};
143
+ if (d.shape != null && HOLD_SHAPES.includes(d.shape)) return { shape: d.shape, declared: true, invalid: null };
144
+ const parsed = parseWakeLine(d.wake);
145
+ const ruling = parsed.ok && parsed.conditions.some((c) => c.kind === 'ruling');
146
+ return { shape: ruling ? 'ask' : 'wait', declared: false, invalid: d.shape != null ? String(d.shape) : null };
147
+ }
148
+
120
149
  /**
121
150
  * `{label, owner, wake, because?}` → the hold comment. `wake` is the field as written (conditions
122
151
  * joined by `, `); pass an array to have it joined. `because` null/absent → the `Hold:` line alone.
123
152
  * The codec writes what it is given — checking `wake` against the vocabulary is `parseWakeLine`'s job.
124
153
  */
125
- function encodeHold({ label, owner, wake, because } = {}) {
154
+ function encodeHold({ label, owner, shape, wake, because } = {}) {
126
155
  const w = Array.isArray(wake) ? wake.join(', ') : wake;
127
- const line = `Hold: ${label} — owner: ${owner} — wake: ${w}`;
156
+ const sh = shape == null ? '' : ` — shape: ${shape}`;
157
+ const line = `Hold: ${label} — owner: ${owner}${sh} — wake: ${w}`;
128
158
  return because == null ? line : `${line}\nBecause: ${because}`;
129
159
  }
130
160
 
@@ -133,20 +163,24 @@ function encodeHold({ label, owner, wake, because } = {}) {
133
163
  * line in the canonical shape. `because` is the second line's text when that line is `Because: …`
134
164
  * and nothing follows it; anything else after the `Hold:` line makes the comment not a hold record
135
165
  * (null) rather than a partially-read one. `wake` is the raw field — `parseWakeLine(wake)` decides
136
- * whether it names a wake at all.
166
+ * whether it names a wake at all. `shape` is present ONLY when the line declares one (#569), as
167
+ * written — `holdShape` decides whether it is in the closed set; absent means "infer from wake".
137
168
  */
138
169
  function decodeHold(body) {
139
170
  const lines = String(body == null ? '' : body).replace(/\r\n/g, '\n').trim().split('\n');
140
171
  const h = HOLD_RE.exec(lines[0]);
141
172
  if (!h) return null;
142
- if (lines.length === 1) return { label: h[1], owner: h[2], wake: h[3], because: null };
173
+ const head = h[3] == null
174
+ ? { label: h[1], owner: h[2], wake: h[4] }
175
+ : { label: h[1], owner: h[2], shape: h[3], wake: h[4] };
176
+ if (lines.length === 1) return { ...head, because: null };
143
177
  const b = lines.length === 2 ? BECAUSE_RE.exec(lines[1]) : null;
144
178
  if (!b) return null;
145
- return { label: h[1], owner: h[2], wake: h[3], because: b[1] };
179
+ return { ...head, because: b[1] };
146
180
  }
147
181
 
148
182
  module.exports = {
149
183
  WAKE_KINDS, CHECKABLE_KINDS, WAKE_KINDS_TEXT,
150
184
  parseWake, parseWakeLine, parseQualifiedIssueRef,
151
- HOLD_RE, BECAUSE_RE, encodeHold, decodeHold,
185
+ HOLD_RE, BECAUSE_RE, HOLD_SHAPES, encodeHold, decodeHold, holdShape,
152
186
  };
@@ -4,7 +4,10 @@
4
4
  * (CONVENTIONS.md §6, *The release rung*), as encode/decode pairs. Pure and synchronous.
5
5
  *
6
6
  * tracking marker — `<!-- colab:release version=vX.Y.Z -->`, the first line of a tracking
7
- * issue's body. Only the marker identifies the version, never the title.
7
+ * issue's body. Only the marker identifies the version, never the title —
8
+ * and only at the START of the body (leading whitespace tolerated): a body
9
+ * that merely MENTIONS the marker further down is talking about releases,
10
+ * not recording one, and is never adopted as the record (#575).
8
11
  * event marker — `<!-- colab:release-event k=v … -->`, one per thing announced on the
9
12
  * tracking issue, keys in the order written. Its exact presence is what makes
10
13
  * a re-run post nothing twice, so key order is part of the wire format.
@@ -16,7 +19,7 @@
16
19
  */
17
20
 
18
21
  const VERSION_RE = /^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
19
- const TRACKING_MARKER_RE = /<!--\s*colab:release\s+version=(v[0-9]+\.[0-9]+\.[0-9]+)\s*-->/;
22
+ const TRACKING_MARKER_RE = /^\s*<!--\s*colab:release\s+version=(v[0-9]+\.[0-9]+\.[0-9]+)\s*-->/;
20
23
  const RELEASE_EVENT_RE = /^<!-- colab:release-event((?: [^\s=]+=\S*)+) -->$/;
21
24
  const RELEASED_COMMENT_RE = /^<!-- colab:release-event released=(\S+) -->\nReleased in \*\*(\S+)\*\* \(`([^`]*)`\)\.$/;
22
25
 
@@ -24,7 +27,7 @@ const RELEASED_COMMENT_RE = /^<!-- colab:release-event released=(\S+) -->\nRelea
24
27
  function encodeTrackingMarker(version) { return `<!-- colab:release version=${version} -->`; }
25
28
 
26
29
  /** The version a body's tracking marker declares, or null — a marker naming a non-canonical
27
- * version (a leading zero) declares nothing. */
30
+ * version (a leading zero) declares nothing, and neither does one anywhere but the body's start. */
28
31
  function decodeTrackingMarker(body) {
29
32
  const m = TRACKING_MARKER_RE.exec(String(body || ''));
30
33
  return m && VERSION_RE.test(m[1]) ? m[1] : null;
@@ -656,6 +656,39 @@
656
656
  "because": null
657
657
  },
658
658
  "note": "synthetic: a Hold line with no Because line"
659
+ },
660
+ {
661
+ "wire": "Hold: blocked:needs-maintainer — owner: maintainer — shape: task — wake: ruling\nBecause: run the signing script on the release machine; only the maintainer holds the key.",
662
+ "decoded": {
663
+ "label": "blocked:needs-maintainer",
664
+ "owner": "maintainer",
665
+ "shape": "task",
666
+ "wake": "ruling",
667
+ "because": "run the signing script on the release machine; only the maintainer holds the key."
668
+ },
669
+ "note": "synthetic (#569): a chore declared as a task — without shape: its `ruling` wake would read as a choice"
670
+ },
671
+ {
672
+ "wire": "Hold: deferred:external-party — owner: upstream maintainers — shape: wait — wake: issueClosed:OWNER/REPO#22, review-by:2026-11-02\nBecause: the design mirrors one still open upstream.",
673
+ "decoded": {
674
+ "label": "deferred:external-party",
675
+ "owner": "upstream maintainers",
676
+ "shape": "wait",
677
+ "wake": "issueClosed:OWNER/REPO#22, review-by:2026-11-02",
678
+ "because": "the design mirrors one still open upstream."
679
+ },
680
+ "note": "synthetic (#569): a declared wait"
681
+ },
682
+ {
683
+ "wire": "Hold: needs-decision — owner: @maintainer — shape: ask — wake: ruling\nBecause: pick the import model; the options block in the body recommends A.",
684
+ "decoded": {
685
+ "label": "needs-decision",
686
+ "owner": "@maintainer",
687
+ "shape": "ask",
688
+ "wake": "ruling",
689
+ "because": "pick the import model; the options block in the body recommends A."
690
+ },
691
+ "note": "synthetic (#569): a declared ask — the choice itself lives in the issue's decision:options block"
659
692
  }
660
693
  ],
661
694
  "notHolds": [
@@ -677,6 +710,18 @@
677
710
  "decoded": "v0.1.6"
678
711
  }
679
712
  ],
713
+ "notTracking": [
714
+ {
715
+ "wire": "Finalize keeps one tracking issue per version; its body starts <!-- colab:release version=v0.1.6 --> and nothing else counts.",
716
+ "decoded": null,
717
+ "note": "synthetic (#575): an issue ABOUT releases that mentions the marker mid-body — never adopted as the record"
718
+ },
719
+ {
720
+ "wire": "fix: release lookup\n\n```\n<!-- colab:release version=v0.1.6 -->\n```",
721
+ "decoded": null,
722
+ "note": "synthetic (#575): the marker quoted on a later line, not the body's first"
723
+ }
724
+ ],
680
725
  "events": [
681
726
  {
682
727
  "wire": "<!-- colab:release-event candidate=v0.1.6-rc.1 -->",
@@ -35,6 +35,7 @@ const DESCRIPTOR = '.github/project.yml';
35
35
  const TUNING = Object.freeze({
36
36
  'ship-batch': (doc) => { const r = shipBatch.parseShipBatch(doc); return r.valid ? null : r.reason; },
37
37
  'ship-batch-wait': (doc) => { const r = shipBatch.parseShipBatchWait(doc); return r.valid ? null : r.reason; },
38
+ [shipBatch.STEPS_KEY]: (doc) => { const r = shipBatch.parseShipBatchSteps(doc); return r.valid ? null : r.reason; },
38
39
  'ci-wait-factor': (doc) => { const r = ciProfile.parseFactor(doc); return r.valid ? null : r.reason; },
39
40
  [thresholds.KEY]: (doc) => { const r = thresholds.parseThresholds(doc); return r.problems.length ? r.problems.join('; ') : null; },
40
41
  });
@@ -49,8 +50,8 @@ const AUTHORITY_KEYS = Object.freeze([
49
50
  'exposure', 'tier', 'trunk', 'deploy', 'release', 'production',
50
51
  ]);
51
52
 
52
- /** A value is a plain YAML scalar — every tuning value is one (`2`, `6m`, `1.5`). */
53
- const VALUE_RE = /^[A-Za-z0-9._-]+$/;
53
+ /** A value is a plain YAML scalar — every tuning value is one (`2`, `6m`, `1.5`, `2,4,8`). */
54
+ const VALUE_RE = /^[A-Za-z0-9._,-]+$/;
54
55
 
55
56
  /**
56
57
  * `ship-batch` → `{ top: 'ship-batch', sub: null }`; `thresholds.hot-file-count` → `{ top:
@@ -89,7 +90,7 @@ function replaceValue(line, value) {
89
90
  * old }` (`old` is the previous raw value, or null when the key was absent), or `{ problem }`.
90
91
  */
91
92
  function editText(text, keyPath, value) {
92
- if (!VALUE_RE.test(String(value))) return { problem: `value ${JSON.stringify(value)} is not a plain scalar (letters, digits, . _ -)` };
93
+ if (!VALUE_RE.test(String(value))) return { problem: `value ${JSON.stringify(value)} is not a plain scalar (letters, digits, . _ , -)` };
93
94
  const src = String(text);
94
95
  const eol = src.endsWith('\n') ? '' : '\n';
95
96
  const lines = src.split('\n');
@@ -358,6 +358,32 @@ function sideText(git, repo, sha) {
358
358
  return r.ok ? r.stdout : null;
359
359
  }
360
360
 
361
+ /**
362
+ * The cure rule's containment read (#281 condition 1), against the ref `ship` actually lands (#589).
363
+ *
364
+ * A `--handoff` land usually has no local branch — only `<remote>/<branch>` — so asking git about
365
+ * the bare name failed, and that failure read as "not an ancestor": a real cure refused until a
366
+ * local ref was made by hand. The ref is resolved here exactly as `shipRefFor` does (local branch,
367
+ * else its remote-tracking ref), and the three outcomes are kept apart:
368
+ * `{ref, contains: true}` · `{ref, contains: false}` (git exit 1 — genuinely not an ancestor) ·
369
+ * `{ref, contains: null, reason}` — the branch or the red sha could not be resolved, or git failed.
370
+ * `null` refuses in `cureVerdict` with the "could not resolve" reason, never "does not contain".
371
+ * Never throws.
372
+ */
373
+ function cureContainment(git, repo, redSha, branch, remote) {
374
+ const refs = git.branchRefs(repo, branch, ...(remote ? [remote] : []));
375
+ const ref = refs.localSha || refs.remoteSha;
376
+ if (!ref) {
377
+ return { ref: null, contains: null,
378
+ reason: `could not resolve ${branch} — no local branch and no remote-tracking ref (fetch it first)` };
379
+ }
380
+ const r = git.git(['merge-base', '--is-ancestor', redSha, ref], repo);
381
+ if (r.ok) return { ref, contains: true, reason: '' };
382
+ if (r.code === 1) return { ref, contains: false, reason: '' };
383
+ return { ref, contains: null,
384
+ reason: `could not resolve trunk's red head \`${redSha}\` against ${branch} (${ref.slice(0, 7)}): ${(r.stderr || '').split('\n')[0] || `git exit ${r.code}`}` };
385
+ }
386
+
361
387
  /**
362
388
  * The diff signals for one branch against trunk, over the merge-base range (`trunk...branch` — the
363
389
  * same tree a squash lands). Returns `{ ok, reason, workflowsTouched, manifestScriptsTouched,
@@ -452,5 +478,5 @@ function pythonSignal(git, repo, trunk, branch, entries) {
452
478
  return { touched: paths.length > 0, paths, reason: '' };
453
479
  }
454
480
 
455
- module.exports = { cureDiffSignals, scriptsBlockDiffers, scriptsAddition, pythonPinChange, parseRequirement,
481
+ module.exports = { cureDiffSignals, cureContainment, scriptsBlockDiffers, scriptsAddition, pythonPinChange, parseRequirement,
456
482
  isPythonManifest, pythonIncludes, ABSENT };
@@ -300,6 +300,47 @@ function evaluateIssue({ labels, comments, labelEvents = null, body, trust } = {
300
300
  return { recorded, gated, contradiction: recorded && gated, pair, pending, decisions, ask, unshapedAsk };
301
301
  }
302
302
 
303
+ /**
304
+ * #582: the ask records on this issue still waiting on an answer — what `colab decision --record`
305
+ * shows the recorder, so the ruling can name the ask it settles (`--answers <id>`). A consumer that
306
+ * tracks asks reads a nameless ruling as answering the issue's ONLY open ask; with two or more it
307
+ * cannot tell which one the ruling meant.
308
+ *
309
+ * An ask is OPEN when no answer comes AFTER its latest ask record (same id; a re-ask at a higher
310
+ * version reopens it). An answer is either an answer record naming the id, or a live `⚖ Decision
311
+ * recorded` whose `answers` field is that id. Order is by `createdAt`, then position inside one
312
+ * comment. Deliberately NOT trust-filtered: this only decides what to SHOW and whether a nameless
313
+ * record is ambiguous — it gates no start and authorizes nothing.
314
+ *
315
+ * Returns [{id, version, at, ns}], oldest-asked first.
316
+ */
317
+ function openAsks(comments) {
318
+ const list = Array.isArray(comments) ? comments : [];
319
+ const sorted = list
320
+ .map((c, i) => ({ c, i }))
321
+ .sort((a, b) => (a.c.createdAt < b.c.createdAt ? -1 : a.c.createdAt > b.c.createdAt ? 1 : a.i - b.i));
322
+ const asks = new Map(); // id -> {id, version, at, ns, pos}
323
+ const answers = []; // {id, pos}
324
+ sorted.forEach(({ c }, ci) => {
325
+ const body = String(c.body || '');
326
+ for (const a of codec.askRecords(body)) {
327
+ asks.set(a.id, { id: a.id, version: a.version, at: c.createdAt || null, ns: a.ns, pos: [ci, a.index] });
328
+ }
329
+ for (const r of codec.answerRecords(body)) answers.push({ id: r.ask, pos: [ci, r.index] });
330
+ });
331
+ const live = new Set(liveDecisions(list).map((d) => d.at));
332
+ sorted.forEach(({ c }, ci) => {
333
+ if (!live.has(c.createdAt)) return;
334
+ const d = codec.decodeDecision(c.body);
335
+ if (d && d.answers && d.answers !== '-') answers.push({ id: d.answers, pos: [ci, 0] });
336
+ });
337
+ const after = (p, q) => p[0] > q[0] || (p[0] === q[0] && p[1] > q[1]);
338
+ return [...asks.values()]
339
+ .filter((a) => !answers.some((r) => r.id === a.id && after(r.pos, a.pos)))
340
+ .sort((a, b) => (after(a.pos, b.pos) ? 1 : -1))
341
+ .map(({ id, version, at, ns }) => ({ id, version, at, ns }));
342
+ }
343
+
303
344
  module.exports = {
304
345
  DECISION_MARK, REOPEN_MARK, DECISION_RE, REOPEN_RE,
305
346
  decisionCommentBody, reopenCommentBody,
@@ -308,4 +349,5 @@ module.exports = {
308
349
  OPTIONS_RE, PAIR_VERDICTS, pairVerdict,
309
350
  MOCKUP_RE, mockupUrls, ASK_SHAPES, askShape,
310
351
  evaluateIssue,
352
+ openAsks,
311
353
  };
@@ -19,6 +19,19 @@ const DOC_EXTENSIONS = Object.freeze(['.md', '.mdx', '.txt']);
19
19
  const DOCS_DIR = 'docs/';
20
20
  /** Rules and agent instructions: never documentation, at any depth, even though they are `.md`. */
21
21
  const NEVER_BASENAMES = Object.freeze(['CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md']);
22
+ /**
23
+ * #570: build inputs that happen to end in `.txt` — a suite installs or compiles from them, so a change
24
+ * to one changes behaviour. Never documentation, at any depth: a Python dependency manifest exactly as
25
+ * the cure rule names one (cure-diff.js isPythonManifest — a name containing `requirements`, or under a
26
+ * `requirements/` directory, any case), a pip constraints file, and `CMakeLists.txt`. A `.txt` pulled
27
+ * in by `-r`/`-c` under some other name is NOT caught by name — a repo with one lists it in
28
+ * `ci-docs-skip`.
29
+ */
30
+ function buildInput(p, base) {
31
+ // Lazy: cure-diff.js requires this module at load time.
32
+ if (require('./cure-diff').isPythonManifest(p)) return true;
33
+ return /constraints.*\.txt$/i.test(base) || base === 'CMakeLists.txt';
34
+ }
22
35
  /** Config directories: nothing under them is documentation, at any depth. */
23
36
  const NEVER_DIRS = Object.freeze(['.claude', '.github', '.githooks']);
24
37
  /**
@@ -40,6 +53,7 @@ function pathReason(p) {
40
53
  const segs = String(p).split('/');
41
54
  const base = segs[segs.length - 1];
42
55
  if (NEVER_BASENAMES.includes(base)) return `${base} is agent rules, not documentation`;
56
+ if (buildInput(String(p), base)) return `${base} is a build input, not documentation`;
43
57
  const dir = segs.slice(0, -1).find((s) => NEVER_DIRS.includes(s));
44
58
  if (dir) return `under ${dir}/ (config)`;
45
59
  const dirs = segs.slice(0, -1);
@@ -164,7 +178,40 @@ function directChanges(git, repo, trunk, since) {
164
178
  return { ...verdict, commits: shas.length };
165
179
  }
166
180
 
181
+ /**
182
+ * #570: `ci-docs-skip:` in project.yml — the opt-in to the CI templates' docs-only mode. Absent (or
183
+ * null) = off. A list = on; each member is a repo path whose changes always run the suite even though
184
+ * this module calls them documentation (`docs/api/` feeding a generator). `[]` = on, nothing excluded.
185
+ *
186
+ * The CI guard parses the same shape in shell and reads anything else as "not opted in" — the
187
+ * stricter direction — so an invalid value here is a finding: a declaration that silently does
188
+ * nothing. Members are plain paths (the guard matches `p == x` or `p` under `x/`): no glob, no `..`
189
+ * or `.` segment, not absolute, only `[A-Za-z0-9._/-]`.
190
+ */
191
+ const CI_DOCS_SKIP_KEY = 'ci-docs-skip';
192
+ function parseCiDocsSkip(doc) {
193
+ const has = !!doc && Object.prototype.hasOwnProperty.call(doc, CI_DOCS_SKIP_KEY);
194
+ const v = has ? doc[CI_DOCS_SKIP_KEY] : null;
195
+ if (v === null || v === undefined) {
196
+ return { declared: false, valid: true, on: false, exclude: null, reason: 'ci-docs-skip absent — a docs-only change runs the full CI suite (#570)' };
197
+ }
198
+ const bad = (why) => ({ declared: true, valid: false, on: false, exclude: null,
199
+ reason: `ci-docs-skip ${why} — it must be a list of repo paths (\`[]\` for none); the CI guard reads anything else as not opted in, so docs-only changes run the full suite` });
200
+ if (!Array.isArray(v)) return bad(`is ${JSON.stringify(v)}`);
201
+ const exclude = [];
202
+ for (const m of v) {
203
+ const s = typeof m === 'string' ? m.replace(/\/+$/, '') : null;
204
+ if (!s || !/^[A-Za-z0-9._/-]+$/.test(s) || s.startsWith('/') || s.split('/').some((x) => x === '..' || x === '.' || x === '')) {
205
+ return bad(`lists ${JSON.stringify(m)}, which is not a plain repo path`);
206
+ }
207
+ exclude.push(s);
208
+ }
209
+ return { declared: true, valid: true, on: true, exclude,
210
+ reason: exclude.length ? `ci-docs-skip on, except ${exclude.join(', ')}` : 'ci-docs-skip on — a docs-only change skips the CI suite' };
211
+ }
212
+
167
213
  module.exports = {
168
214
  DOC_EXTENSIONS, DOCS_DIR, NEVER_BASENAMES, NEVER_DIRS, NEVER_SUBDIRS,
169
215
  pathReason, classify, parseRaw, parseBinary, readEntries, branchChanges, directChanges,
216
+ CI_DOCS_SKIP_KEY, parseCiDocsSkip,
170
217
  };
package/tools/lib/git.js CHANGED
@@ -19,16 +19,32 @@ function run(cmd, args, opts = {}) {
19
19
  const { timeoutMs, ...spawnOpts } = opts;
20
20
  const res = spawnSync(cmd, args, { encoding: 'utf8', ...(timeoutMs ? { timeout: timeoutMs } : {}), ...spawnOpts });
21
21
  const timedOut = !!(res.error && res.error.code === 'ETIMEDOUT');
22
+ const stderr = (res.stderr || '').trim();
22
23
  return {
23
- ok: res.status === 0 && !timedOut,
24
+ ok: res.status === 0 && !timedOut && !res.error,
24
25
  code: res.status,
25
26
  stdout: (res.stdout || '').trim(),
26
- stderr: timedOut ? `timed out after ${timeoutMs}ms with no output` : (res.stderr || '').trim(),
27
+ // A spawn error (#585) leaves stderr empty: ENOBUFS kills the child once stdout passes
28
+ // `maxBuffer` (1 MiB by default), ENOENT means the binary is missing. An empty detail then
29
+ // reads as "git said nothing" and a caller's remedy guesses at the wrong cause, so the error
30
+ // itself becomes the detail whenever the child wrote none.
31
+ stderr: timedOut ? `timed out after ${timeoutMs}ms with no output` : (stderr || spawnErrorLine(res.error, spawnOpts)),
27
32
  error: res.error || null,
28
33
  timedOut,
29
34
  };
30
35
  }
31
36
 
37
+ /** One line naming a spawn error, or '' for none. ENOBUFS names the buffer it overran (#585). */
38
+ function spawnErrorLine(error, spawnOpts = {}) {
39
+ if (!error) return '';
40
+ const code = error.code || 'error';
41
+ if (code === 'ENOBUFS') {
42
+ const max = spawnOpts.maxBuffer || 1024 * 1024;
43
+ return `ENOBUFS: output passed the ${Math.round(max / 1024)} KiB read buffer and the child was killed`;
44
+ }
45
+ return `${code}: ${error.message || 'spawn failed'}`;
46
+ }
47
+
32
48
  /**
33
49
  * Every `gh` spawn in this module goes through the tracker adapter (#500) — the one place the CLI
34
50
  * talks to GitHub. Lazy require, deliberately: `module.exports = {…}` below REPLACES the exports
@@ -691,6 +707,30 @@ function ghPrForBranch(repo, branch) {
691
707
  } catch (_) { return { error: 'gh pr list returned unparseable JSON' }; }
692
708
  }
693
709
 
710
+ /**
711
+ * #584: EVERY open pull request whose head is `branch` — not just the first, as ghPrForBranch
712
+ * returns — so `colab ship` can close each CI-trigger PR its squash left behind. `{ prs }` on
713
+ * success (possibly empty), `{ error }` when the read failed; never conflate the two.
714
+ */
715
+ function ghOpenPrsForBranch(repo, branch) {
716
+ const r = gh(['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number,url,headRefOid,headRefName'], { cwd: repo });
717
+ if (!r.ok) return { error: (r.stderr || '').split('\n')[0] || `gh pr list exited ${r.code}` };
718
+ try {
719
+ const list = JSON.parse(r.stdout || '[]');
720
+ return { prs: Array.isArray(list) ? list : [] };
721
+ } catch (_) { return { error: 'gh pr list returned unparseable JSON' }; }
722
+ }
723
+
724
+ /** #584: every open pull request in the repo, for `colab doctor --sync`'s landed-PR listing. */
725
+ function ghOpenPrs(repo) {
726
+ const r = gh(['pr', 'list', '--state', 'open', '--limit', '200', '--json', 'number,url,headRefOid,headRefName'], { cwd: repo });
727
+ if (!r.ok) return { error: (r.stderr || '').split('\n')[0] || `gh pr list exited ${r.code}` };
728
+ try {
729
+ const list = JSON.parse(r.stdout || '[]');
730
+ return { prs: Array.isArray(list) ? list : [] };
731
+ } catch (_) { return { error: 'gh pr list returned unparseable JSON' }; }
732
+ }
733
+
694
734
  /**
695
735
  * #367: the forge's visibility for this repo — "PUBLIC" | "PRIVATE" | "INTERNAL" — or null when it
696
736
  * could not be read (no gh, no GitHub remote, offline). Null is "could not read", never "private":
@@ -1042,7 +1082,7 @@ function ghInstalled() {
1042
1082
  function ghRunsForRef(repo, ref, sha, limit = 20) {
1043
1083
  if (!sha) return null;
1044
1084
  const r = gh(['run', 'list', '--branch', ref, '-L', String(limit),
1045
- '--json', 'headSha,status,conclusion,createdAt,databaseId,workflowName,attempt'], { cwd: repo });
1085
+ '--json', 'headSha,status,conclusion,createdAt,updatedAt,databaseId,workflowName,attempt'], { cwd: repo });
1046
1086
  if (!r.ok) return null;
1047
1087
  let runs;
1048
1088
  try { runs = JSON.parse(r.stdout); } catch (_) { return null; }
@@ -1203,6 +1243,12 @@ function isNewerRun(a, b) {
1203
1243
  * sha — otherwise a cancel-in-progress straggler created after the passing run would turn #92's
1204
1244
  * green back into "every run was cancelled". It still counts when it is all a workflow has.
1205
1245
  *
1246
+ * #514: `skipped` is neutral in exactly the same way. A run whose every job was skipped executed
1247
+ * nothing (a same-repo `pull_request` run gated off by a fork-PR `if:`, a `workflow_run` that
1248
+ * declined), so a newer `skipped` row never stands for a workflow that has a run that ran: push
1249
+ * `failure` + newer `skipped` reads red, push `success` + newer `skipped` reads green. A workflow
1250
+ * whose runs are ALL skipped still reads not-green, as before.
1251
+ *
1206
1252
  * Newest = later createdAt, then higher databaseId; when neither key separates two rows, gh's
1207
1253
  * newest-first order decides (the first row seen is kept). An unfinished newest run still blocks
1208
1254
  * green (#307): it is the head, so the all-finished quantifier sees it.
@@ -1210,6 +1256,9 @@ function isNewerRun(a, b) {
1210
1256
  * Returns the heads in their original order (callers' newest-first `forSha[0]` pick relies on it)
1211
1257
  * plus the rows they superseded.
1212
1258
  */
1259
+ /** Conclusions of a run that executed nothing — never chosen over a run that did (#92, #514). */
1260
+ const NEUTRAL_RUN = new Set(['cancelled', 'skipped']);
1261
+
1213
1262
  function newestRunPerWorkflow(rows) {
1214
1263
  const best = new Map();
1215
1264
  rows.forEach((x, i) => {
@@ -1218,9 +1267,9 @@ function newestRunPerWorkflow(rows) {
1218
1267
  const cur = best.get(name);
1219
1268
  if (cur === undefined) { best.set(name, i); return; }
1220
1269
  const c = rows[cur];
1221
- const xCancelled = x.conclusion === 'cancelled';
1222
- const cCancelled = c.conclusion === 'cancelled';
1223
- if (xCancelled !== cCancelled) { if (cCancelled) best.set(name, i); return; }
1270
+ const xNeutral = NEUTRAL_RUN.has(x.conclusion);
1271
+ const cNeutral = NEUTRAL_RUN.has(c.conclusion);
1272
+ if (xNeutral !== cNeutral) { if (cNeutral) best.set(name, i); return; }
1224
1273
  if (isNewerRun(x, c)) best.set(name, i);
1225
1274
  });
1226
1275
  const heads = []; const superseded = [];
@@ -1382,7 +1431,7 @@ function ghAssignedIssues(repo) {
1382
1431
 
1383
1432
  module.exports = {
1384
1433
  ghCommitCheckRuns, ghCheckRunAnnotations,
1385
- run, git, repoRoot, mainRepoRoot, originUrl, remoteInfo, remoteName, remoteFor, remoteUrl, remoteProblem, _resetRemoteCache,
1434
+ run, spawnErrorLine, git, repoRoot, mainRepoRoot, originUrl, remoteInfo, remoteName, remoteFor, remoteUrl, remoteProblem, _resetRemoteCache,
1386
1435
  detectTrunk, branchExists, branchRefs, existingBranchRef,
1387
1436
  claimRemote, remoteHeads, parseRemoteHeads, CLAIM_REF_PREFIX, claimRef, pushClaimRef, deleteClaimRef,
1388
1437
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
@@ -1392,5 +1441,5 @@ module.exports = {
1392
1441
  ghRunJobCount, ghRunJobs, ghWorkflowDispatch,
1393
1442
  ghIssueListByLabel, ghLabelDelete, ghLabelCreate, ghListLabelsDetailed, ghLabelEditDescription,
1394
1443
  ghApi, isGraphqlRateLimit, ghIssueRelease, ghClaimHolder, ghIssueLabelEvents, ghIssueLabelActors,
1395
- ghPrForBranch, ghPrCreate, ghPrClose, ghRepoVisibility,
1444
+ ghPrForBranch, ghOpenPrsForBranch, ghOpenPrs, ghPrCreate, ghPrClose, ghRepoVisibility,
1396
1445
  };
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+ /**
3
+ * The migration-grant policy's ONE precedence (#598): the repo's explicit `migration-grant:` >
4
+ * this machine's value > `human`. Every reader resolves through here — `colab migration-grant`
5
+ * (mint and --list), `colab ship`, and any console on the same machine that imports this module —
6
+ * so none of them can compute a different answer than the gate does.
7
+ *
8
+ * THE MACHINE VALUE lives in this machine's colab config (`~/.colab/config.json`, or
9
+ * `$COLAB_HOME/config.json`), under `policy["migration-grant"]`:
10
+ * { "value": "human" | "reviewer", "by": "<who>", "at": "<ISO>", "host": "<hostname>", "machine": "<id>|null" }
11
+ * Written only by `COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>` — the
12
+ * human gate is in tools/colab, before anything is parsed. Its reach is ONE machine: a ship run on
13
+ * another machine never sees it and resolves to `human`, which is the safe direction.
14
+ * `machine` binds the record to the machine that wrote it, so a dotfile-synced or copied config
15
+ * does not carry the switch to another box (read: 'foreign'). Where either side has no machine id,
16
+ * the binding is skipped.
17
+ *
18
+ * THE OWNER-LEVEL RECORD (#596) IS NOT A RUNG. It was a tracker comment any org member could post,
19
+ * including the shared account agent sessions post from, and it reached every repo of the owner
20
+ * (#598, docs/adr/539-migration-rationale.md). `colab owner-policy show` still reads it, read-only.
21
+ *
22
+ * A CONSOLE: call `effectiveGrantPolicy(doc)` with the project.yml the gate reads (the trunk
23
+ * checkout for a mint, the merge target for ship). It reads the same config file colab does —
24
+ * pass `{ configFile }` explicitly if the console process does not inherit colab's COLAB_HOME.
25
+ *
26
+ * Everything here is pure except `readMachinePolicy` (and `effectiveGrantPolicy`, which calls it).
27
+ */
28
+ const fs = require('fs');
29
+ const migrationGrant = require('./migration-grant');
30
+
31
+ const MACHINE_KEY = 'migration-grant';
32
+ const CONFIG_SECTION = 'policy';
33
+ const VALUES = ['human', 'reviewer'];
34
+ const UNSET = 'unset';
35
+
36
+ /**
37
+ * The machine record from a parsed config.json object. Pure.
38
+ * Returns { read: 'ok'|'none'|'invalid'|'foreign', set, value, by, at, host, machine, why }.
39
+ * Anything but read 'ok' is unset.
40
+ */
41
+ function machinePolicyFrom(cfg, { machineId = null } = {}) {
42
+ const sec = cfg && typeof cfg === 'object' ? cfg[CONFIG_SECTION] : null;
43
+ const rec = sec && typeof sec === 'object' ? sec[MACHINE_KEY] : undefined;
44
+ const empty = { set: false, value: null, by: null, at: null, host: null, machine: null };
45
+ if (rec === undefined || rec === null) return { read: 'none', ...empty, why: '' };
46
+ if (typeof rec !== 'object' || Array.isArray(rec) || !VALUES.includes(rec.value)) {
47
+ return { read: 'invalid', ...empty, why: `${CONFIG_SECTION}.${MACHINE_KEY} in the machine config is not a human|reviewer record` };
48
+ }
49
+ const bits = { value: rec.value, by: rec.by || null, at: rec.at || null, host: rec.host || null, machine: rec.machine || null };
50
+ if (bits.machine && machineId && bits.machine !== machineId) {
51
+ return { read: 'foreign', ...empty, why: `the machine-level value was written on another machine (${bits.host || bits.machine}) — a copied config does not carry it` };
52
+ }
53
+ return { read: 'ok', set: true, ...bits, why: '' };
54
+ }
55
+
56
+ function defaultConfigFile() { return require('./state').CONFIG_FILE; }
57
+ function defaultMachineId() {
58
+ try { return require('./machine').localMachine().id || null; } catch (_) { return null; }
59
+ }
60
+
61
+ /** The machine record, read from disk. Never throws: an unreadable file reads as unset. */
62
+ function readMachinePolicy({ configFile, machineId } = {}) {
63
+ const file = configFile || defaultConfigFile();
64
+ let raw;
65
+ try { raw = fs.readFileSync(file, 'utf8'); } catch (e) {
66
+ if (e && e.code === 'ENOENT') return machinePolicyFrom({}, {});
67
+ return { read: 'unread', set: false, value: null, why: `${file}: ${e.message}` };
68
+ }
69
+ let cfg;
70
+ try { cfg = JSON.parse(raw); } catch (e) { return { read: 'unread', set: false, value: null, why: `${file} is not valid JSON` }; }
71
+ return machinePolicyFrom(cfg, { machineId: machineId === undefined ? defaultMachineId() : machineId });
72
+ }
73
+
74
+ /**
75
+ * The precedence. `repoPol` = migration-grant.js parseGrantPolicy(doc); `machine` = a
76
+ * machinePolicyFrom/readMachinePolicy result, or null. Returns repoPol's shape plus
77
+ * { source: 'repo'|'machine'|'default', optedOut, machineBy, machineAt, machineHost, machineNote }.
78
+ * `reason` names the source — callers print it on refusal. Pure.
79
+ */
80
+ function resolveGrantPolicy(repoPol, machine) {
81
+ const m = machine || null;
82
+ const set = !!(m && m.read === 'ok' && m.set);
83
+ const bits = set ? { machineBy: m.by || null, machineAt: m.at || null, machineHost: m.host || null }
84
+ : { machineBy: null, machineAt: null, machineHost: null };
85
+ if (repoPol.declared) {
86
+ const optedOut = repoPol.valid && repoPol.policy === 'human' && set && m.value === 'reviewer';
87
+ return { ...repoPol, source: 'repo', optedOut, ...bits, machineNote: '',
88
+ reason: optedOut
89
+ ? `this repo opted out: project.yml declares migration-grant: human, which wins over this machine's reviewer value (set by ${m.by} at ${m.at})`
90
+ : repoPol.reason };
91
+ }
92
+ if (set) {
93
+ return { policy: m.value, declared: false, valid: true, source: 'machine', optedOut: false, ...bits, machineNote: '',
94
+ reason: `machine-level migration-grant: ${m.value} (set by ${m.by || '?'} at ${m.at || '?'} on ${m.host || 'this machine'}; this repo declares no key of its own)` };
95
+ }
96
+ const machineNote = m && (m.read === 'unread' || m.read === 'invalid' || m.read === 'foreign')
97
+ ? `the machine-level value is not usable (${m.why || m.read}) — read as unset` : '';
98
+ return { ...repoPol, source: 'default', optedOut: false, ...bits, machineNote,
99
+ reason: machineNote ? `${repoPol.reason}; ${machineNote}` : repoPol.reason };
100
+ }
101
+
102
+ /** The one call a console makes: the policy for `doc`, against this machine's config. */
103
+ function effectiveGrantPolicy(doc, opts = {}) {
104
+ return resolveGrantPolicy(migrationGrant.parseGrantPolicy(doc), readMachinePolicy(opts));
105
+ }
106
+
107
+ /** One-line source label: `repo`, `machine (<by> at <at>)`, or `default`. */
108
+ function sourceLabel(res) {
109
+ if (!res) return 'default';
110
+ if (res.source === 'machine') return `machine (${res.machineBy || '?'} at ${res.machineAt || '?'})`;
111
+ return res.source;
112
+ }
113
+
114
+ /** The stored record. Pure. */
115
+ function recordFor(value, { by = null, at = null, host = null, machine = null } = {}) {
116
+ if (!VALUES.includes(value)) throw new Error(`grant-policy: ${JSON.stringify(value)} is not one of ${VALUES.join(' | ')}`);
117
+ return { value, by, at, host, machine };
118
+ }
119
+
120
+ /** A new config object with the machine value set (or removed, on `unset`). Every other key kept. Pure. */
121
+ function withValue(cfg, value, meta = {}) {
122
+ const next = { ...(cfg || {}) };
123
+ const sec = { ...(next[CONFIG_SECTION] && typeof next[CONFIG_SECTION] === 'object' ? next[CONFIG_SECTION] : {}) };
124
+ if (value === UNSET) delete sec[MACHINE_KEY];
125
+ else sec[MACHINE_KEY] = recordFor(value, meta);
126
+ if (Object.keys(sec).length) next[CONFIG_SECTION] = sec; else delete next[CONFIG_SECTION];
127
+ return next;
128
+ }
129
+
130
+ module.exports = {
131
+ MACHINE_KEY, CONFIG_SECTION, VALUES, UNSET,
132
+ machinePolicyFrom, readMachinePolicy, resolveGrantPolicy, effectiveGrantPolicy, sourceLabel, recordFor, withValue,
133
+ };