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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +248 -213
  2. package/README.vi.md +252 -186
  3. package/audit/audit.mjs +193 -10
  4. package/package.json +7 -1
  5. package/templates/README.md +30 -2
  6. package/templates/ci-laravel.yml +102 -21
  7. package/templates/ci-node.yml +61 -3
  8. package/templates/ci-python.yml +52 -3
  9. package/templates/deploy-adapter-portainer.mjs +206 -0
  10. package/templates/deploy-container-run.mjs +368 -0
  11. package/templates/deploy-container.yml +219 -0
  12. package/templates/dist-refs.yml +6 -0
  13. package/templates/docs-lint.mjs +1 -1
  14. package/templates/npx-launcher.mjs +118 -20
  15. package/templates/npx-service.mjs +828 -0
  16. package/templates/release-auto.yml +341 -32
  17. package/tools/colab +1902 -278
  18. package/tools/lib/adopt.js +373 -14
  19. package/tools/lib/branch-name.js +29 -1
  20. package/tools/lib/ci-cure.js +522 -31
  21. package/tools/lib/ci-grant.js +289 -22
  22. package/tools/lib/ci-wait.js +223 -0
  23. package/tools/lib/claim-comments.js +13 -64
  24. package/tools/lib/claim-identity.js +42 -7
  25. package/tools/lib/codec/claim.d.ts +41 -0
  26. package/tools/lib/codec/claim.js +153 -0
  27. package/tools/lib/codec/decision.d.ts +29 -0
  28. package/tools/lib/codec/decision.js +81 -0
  29. package/tools/lib/codec/grants.d.ts +82 -0
  30. package/tools/lib/codec/grants.js +268 -0
  31. package/tools/lib/codec/hold.d.ts +26 -0
  32. package/tools/lib/codec/hold.js +152 -0
  33. package/tools/lib/codec/index.d.ts +21 -0
  34. package/tools/lib/codec/index.js +32 -0
  35. package/tools/lib/codec/labels.d.ts +65 -0
  36. package/tools/lib/codec/labels.js +723 -0
  37. package/tools/lib/codec/markers.d.ts +35 -0
  38. package/tools/lib/codec/markers.js +138 -0
  39. package/tools/lib/codec/release.d.ts +17 -0
  40. package/tools/lib/codec/release.js +69 -0
  41. package/tools/lib/codec/samples.json +778 -0
  42. package/tools/lib/codeowners.js +68 -4
  43. package/tools/lib/container-close.js +38 -0
  44. package/tools/lib/cure-diff.js +198 -9
  45. package/tools/lib/decision-record.js +15 -39
  46. package/tools/lib/docs-only.js +15 -1
  47. package/tools/lib/exposure-shape.js +42 -8
  48. package/tools/lib/git.js +324 -42
  49. package/tools/lib/group-labels.js +65 -0
  50. package/tools/lib/install-check.js +14 -8
  51. package/tools/lib/install-route.js +139 -0
  52. package/tools/lib/instruction-file.js +1 -0
  53. package/tools/lib/labels.js +22 -647
  54. package/tools/lib/local-adopt.js +8 -4
  55. package/tools/lib/migration-grant.js +206 -104
  56. package/tools/lib/place.js +2 -2
  57. package/tools/lib/release-cut.js +199 -25
  58. package/tools/lib/release-finalize.js +111 -23
  59. package/tools/lib/release-policy.js +130 -22
  60. package/tools/lib/release-runner.js +125 -0
  61. package/tools/lib/release-tag.js +3 -1
  62. package/tools/lib/scratch-dirs.js +118 -0
  63. package/tools/lib/ship-batch.js +36 -1
  64. package/tools/lib/ship-human-door.js +76 -0
  65. package/tools/lib/stamp.js +7 -0
  66. package/tools/lib/tracker-fake.js +195 -0
  67. package/tools/lib/tracker-github.js +106 -0
  68. package/tools/lib/tracker-scenarios.json +206 -0
  69. package/tools/lib/tracker.js +64 -0
  70. package/tools/lib/tree-green.js +88 -0
  71. package/tools/lib/util.js +17 -1
  72. package/tools/lib/verify-runs.js +104 -0
  73. package/tools/lib/wake.js +8 -90
  74. package/tools/lib/workflow-triggers.js +48 -0
@@ -121,6 +121,62 @@ function inert(rules, authors) {
121
121
  return { inert: false, reason: `CODEOWNERS names ${others.join(', ')}` };
122
122
  }
123
123
 
124
+ /**
125
+ * #483 — the owner (user or org) of a forge remote URL, lowercased, or null when the URL has no
126
+ * `<owner>/<repo>` shape this can read. Handles `https://host/owner/repo(.git)`,
127
+ * `ssh://git@host[:port]/owner/repo` and the scp form `git@host:owner/repo`.
128
+ */
129
+ function remoteOwner(url) {
130
+ const s = String(url || '').trim().replace(/\/+$/, '').replace(/\.git$/, '');
131
+ let m = /^[a-z][a-z0-9+.-]*:\/\/[^/]+\/([^/]+)\/[^/]+$/i.exec(s);
132
+ if (!m) m = /^[^@/\s]+@[^:/\s]+:([^/]+)\/[^/]+$/.exec(s);
133
+ return m ? m[1].toLowerCase() : null;
134
+ }
135
+
136
+ const TEAM_RE = /^@([^/\s@]+)\/[^/\s]+$/;
137
+
138
+ /**
139
+ * #483 — the owner tokens a FORK must not be bound by: teams (`@org/team`) of an org other than
140
+ * the fork's own owner (`ownOrg`). A fork inherits the upstream's CODEOWNERS unchanged, and a team
141
+ * of another org cannot review in the fork at all, so honouring it would turn every landing into a
142
+ * human gate nobody here decided on (CONVENTIONS.md §2, *Core paths*, "A fork's inherited
143
+ * CODEOWNERS").
144
+ *
145
+ * Narrow on purpose — every doubt still resolves toward review: not a fork, or the fork's owner
146
+ * unknown, drops nothing; a login or an email is never dropped (a person can be a collaborator
147
+ * anywhere); a team of the fork's own org is kept.
148
+ */
149
+ function foreignTeams(rules, { fork, ownOrg } = {}) {
150
+ if (!fork || !ownOrg) return [];
151
+ const own = String(ownOrg).toLowerCase();
152
+ const out = new Set();
153
+ for (const r of rules || []) {
154
+ for (const o of r.owners) {
155
+ const m = TEAM_RE.exec(o);
156
+ if (m && m[1].toLowerCase() !== own) out.add(o);
157
+ }
158
+ }
159
+ return [...out];
160
+ }
161
+
162
+ /**
163
+ * #483 — `rules` with `foreignTeams` removed from every rule's owners. A rule left with no owner
164
+ * stays in place and, like an ownerless line, carves its paths out (the last match still wins), so
165
+ * an inherited `* @upstream/team` leaves the fork's own later lines exactly as they were.
166
+ * Returns `{ rules, dropped }`; `dropped` is `[]` (and `rules` the input) when nothing applies.
167
+ */
168
+ function dropForeignTeams(rules, ctx) {
169
+ const dropped = foreignTeams(rules, ctx);
170
+ if (!dropped.length) return { rules, dropped };
171
+ const gone = new Set(dropped);
172
+ return { rules: (rules || []).map((r) => ({ ...r, owners: r.owners.filter((o) => !gone.has(o)) })), dropped };
173
+ }
174
+
175
+ /** #483: the one-line reason a fork's foreign teams were ignored — shared by every reader. */
176
+ function foreignNote(dropped, ctx) {
177
+ return `fork of an upstream: ignored ${dropped.join(', ')} — team(s) of an org other than ${ctx.ownOrg}, inherited and unable to review here (#483)`;
178
+ }
179
+
124
180
  /**
125
181
  * Has a PR been approved by someone other than its author, AT `headSha`?
126
182
  *
@@ -168,8 +224,10 @@ function approvalVerdict(reviews, { prAuthor, authors = [], headSha }) {
168
224
  * rule is inert only when every file present is inert. Identical texts count once.
169
225
  * `changed`: every path the unit's commits touched, or null when they could not be listed. Null
170
226
  * refuses while the rule is active: an unbounded unit cannot be shown to avoid core paths.
227
+ * `fork`: `{ fork, ownOrg }` (#483) — on a fork, teams of another org are dropped from both files
228
+ * before anything else is read (`dropForeignTeams`). Absent = nothing dropped.
171
229
  */
172
- function directVerdict({ files, authors, changed }) {
230
+ function directVerdict({ files, authors, changed, fork = null }) {
173
231
  const out = { active: false, inertReason: null, codeownersPath: null, warnings: [], corePaths: [], verdict: 'inert', detail: '' };
174
232
  const seen = new Set();
175
233
  const present = (files || []).filter((f) => f && !seen.has(f.text) && seen.add(f.text));
@@ -178,8 +236,11 @@ function directVerdict({ files, authors, changed }) {
178
236
  const inertReasons = [];
179
237
  const activeReasons = [];
180
238
  for (const f of present) {
181
- const { rules, warnings } = parse(f.text);
182
- for (const w of warnings) out.warnings.push(`${f.path}@${f.ref}: ${w}`);
239
+ const parsed = parse(f.text);
240
+ for (const w of parsed.warnings) out.warnings.push(`${f.path}@${f.ref}: ${w}`);
241
+ // #483: a fork's inherited foreign-org teams bind neither file.
242
+ const { rules, dropped } = dropForeignTeams(parsed.rules, fork || {});
243
+ if (dropped.length) out.warnings.push(`${f.path}@${f.ref}: ${foreignNote(dropped, fork)}`);
183
244
  const iv = inert(rules, authors);
184
245
  if (iv.inert) { inertReasons.push(`${f.path}@${f.ref}: ${iv.reason}`); continue; }
185
246
  out.active = true;
@@ -205,4 +266,7 @@ function directVerdict({ files, authors, changed }) {
205
266
  return out;
206
267
  }
207
268
 
208
- module.exports = { CODEOWNERS_PATHS, parse, compile, ownerOf, corePaths, inert, approvalVerdict, directVerdict };
269
+ module.exports = {
270
+ CODEOWNERS_PATHS, parse, compile, ownerOf, corePaths, inert, approvalVerdict, directVerdict,
271
+ remoteOwner, foreignTeams, dropForeignTeams, foreignNote,
272
+ };
@@ -135,7 +135,45 @@ function containerFinding(c) {
135
135
  }
136
136
  }
137
137
 
138
+ /**
139
+ * `owner/repo` from an issue's web URL (`https://<host>/<owner>/<repo>/issues/<n>`), lowercased —
140
+ * GitHub slugs are case-insensitive. null when the URL is absent or not that shape.
141
+ */
142
+ function issueRepoSlug(url) {
143
+ const m = /^https?:\/\/[^/]+\/([^/]+)\/([^/]+)\/issues\/\d+\/?$/.exec(String(url || '').trim());
144
+ return m ? `${m[1]}/${m[2]}`.toLowerCase() : null;
145
+ }
146
+
147
+ /**
148
+ * Is a native parent in the CHILD's own repository (#502)? A sub-issue may have a parent in another
149
+ * repository, and `gh issue view <number>` in the child's repo then reads either nothing or an
150
+ * UNRELATED issue that happens to share the number — one that could be classified, and closed.
151
+ * So a parent is looked up by number only when both URLs prove it lives where the child does.
152
+ *
153
+ * @param {object} childView the child's view, carrying `url` and `parent` ({ number, url })
154
+ * @returns {{relation:'same'|'other'|'unknown', slug:string|null, number:number|null}}
155
+ * `other` carries the parent's `owner/repo`; `unknown` means a URL was missing or unparseable —
156
+ * fail toward leaving the parent alone, the module's asymmetry.
157
+ */
158
+ function parentRelation(childView) {
159
+ const parent = childView && childView.parent;
160
+ const number = parent && Number.isInteger(parent.number) ? parent.number : null;
161
+ const childSlug = issueRepoSlug(childView && childView.url);
162
+ const parentSlug = issueRepoSlug(parent && parent.url);
163
+ if (!childSlug || !parentSlug) return { relation: 'unknown', slug: parentSlug, number };
164
+ return { relation: childSlug === parentSlug ? 'same' : 'other', slug: parentSlug, number };
165
+ }
166
+
167
+ /** One report line for a parent that is not looked up in the child's repo (#502); null for `same`. */
168
+ function parentRelationFinding(rel) {
169
+ const n = rel.number !== null ? `#${rel.number}` : 'parent';
170
+ if (rel.relation === 'other') return `${rel.slug}${n} is in another repository — not evaluated`;
171
+ if (rel.relation === 'unknown') return `${n}: could not tell which repository the parent is in (no issue URL) — not evaluated`;
172
+ return null;
173
+ }
174
+
138
175
  module.exports = {
139
176
  EPIC_LABEL, RELEASE_RECORD_RE,
177
+ issueRepoSlug, parentRelation, parentRelationFinding,
140
178
  untickedItems, classifyContainer, containerDeliveryLabels, containerCloseComment, containerFinding,
141
179
  };
@@ -48,6 +48,26 @@
48
48
  * (`poetry.lock`, `uv.lock`, `Pipfile.lock`) are NOT read by the template and do not count; an
49
49
  * adopter whose CI installs from one has edited the template and owns extending this list.
50
50
  *
51
+ * TWO NARROW ADMISSIONS (#475, #476) — the signals above stay whole (any change still sets the flag),
52
+ * and next to each sits a classifier saying whether EVERY touched manifest's change is of one shape
53
+ * the verdict may admit on step evidence (tools/lib/ci-cure.js):
54
+ *
55
+ * - `manifestScriptsAddOnly` (#475) — every touched `package.json` exists on both sides, keeps every
56
+ * base script byte-for-byte (canonically), and only ADDS keys. Adding a script makes the Node
57
+ * template run more, never less. An added npm LIFECYCLE hook is not admitted: `postinstall`,
58
+ * `prepare`, or `pre<x>`/`post<x>` for a script `<x>` run inside a step that already exists and
59
+ * can rewrite what that step measures (e.g. replace a test binary) without a name changing.
60
+ * - `pythonPinOnly` (#476) — every touched Python manifest exists on both sides and differs ONLY in
61
+ * the version specifier (or `--hash`) of requirements present at the same position on both sides:
62
+ * no requirement added, removed, reordered or renamed, no extras or marker changed, and no option
63
+ * line (`-r`/`-c`/`-e`/index) changed. Requirements files are read line-wise; a `pyproject.toml`
64
+ * only inside its dependency arrays (`[project] dependencies`, `[project.optional-dependencies]`,
65
+ * `[dependency-groups]`, `[build-system] requires`) — every other byte must match. `setup.py` is
66
+ * code and `setup.cfg` is not read here: a change to either is never pin-only.
67
+ *
68
+ * Each classifier is `null` whenever the shape is not met (or not measurable) — which leaves the
69
+ * condition refusing exactly as before. It is a list of what changed when it IS met.
70
+ *
51
71
  * FAIL CLOSED. Every unmeasurable input is `null`, never `false`: a failed diff read, a manifest
52
72
  * blob that could not be read, a manifest that does not parse, a manifest that is a symlink or a
53
73
  * submodule. ci-cure.js's `cureVerdict` refuses on `null`.
@@ -187,6 +207,150 @@ function scriptsBlockDiffers(baseText, headText) {
187
207
  return a !== b;
188
208
  }
189
209
 
210
+ /** The `scripts` object as the Node template reads it, or null when not a JSON object / not an
211
+ * object-valued `scripts`. */
212
+ function scriptsObject(text) {
213
+ let obj;
214
+ try { obj = JSON.parse(String(text).replace(/^/, '')); } catch (_) { return null; }
215
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null;
216
+ const sc = obj.scripts === undefined ? {} : obj.scripts;
217
+ if (!sc || typeof sc !== 'object' || Array.isArray(sc)) return null;
218
+ return sc;
219
+ }
220
+
221
+ /** npm runs these on its own (install, publish, pack) — never by a template step naming them. */
222
+ const NPM_LIFECYCLE = new Set(['preinstall', 'install', 'postinstall', 'prepare', 'prepublish',
223
+ 'prepublishOnly', 'prepack', 'postpack', 'dependencies', 'preuninstall', 'uninstall', 'postuninstall']);
224
+ /** Scripts npm knows by name, whose `pre`/`post` hooks fire even when the script itself is absent. */
225
+ const NPM_BUILTIN = new Set(['install', 'uninstall', 'publish', 'pack', 'test', 'start', 'stop', 'restart',
226
+ 'version', 'shrinkwrap']);
227
+
228
+ /** Whether adding script `key` (to a block whose keys are `keys`) adds a hook npm fires implicitly. */
229
+ function isLifecycleKey(key, keys) {
230
+ if (NPM_LIFECYCLE.has(key)) return true;
231
+ const m = /^(pre|post)(.+)$/.exec(key);
232
+ return !!m && (keys.has(m[2]) || NPM_BUILTIN.has(m[2]));
233
+ }
234
+
235
+ /**
236
+ * PURE (#475). Whether a `package.json` scripts change is ADD-ONLY. Returns `{added: [names]}` when
237
+ * both sides are present, every base key is kept with an identical command, at least one key was
238
+ * added, and no added key is an npm lifecycle hook — else null (not admissible, or unmeasurable).
239
+ */
240
+ function scriptsAddition(baseText, headText) {
241
+ if (baseText === ABSENT || headText === ABSENT || baseText === null || headText === null) return null;
242
+ const a = scriptsObject(baseText);
243
+ const b = scriptsObject(headText);
244
+ if (!a || !b) return null;
245
+ for (const k of Object.keys(a)) {
246
+ if (!Object.prototype.hasOwnProperty.call(b, k) || canonical(a[k]) !== canonical(b[k])) return null;
247
+ }
248
+ const keys = new Set(Object.keys(b));
249
+ const added = Object.keys(b).filter((k) => !Object.prototype.hasOwnProperty.call(a, k));
250
+ if (!added.length) return null;
251
+ if (added.some((k) => typeof b[k] !== 'string' || isLifecycleKey(k, keys))) return null;
252
+ return { added: added.sort() };
253
+ }
254
+
255
+ const SPEC_RE = /^(?:(?:~=|===|==|!=|<=|>=|<|>)\s*[A-Za-z0-9.*+!_-]+\s*)(?:,\s*(?:~=|===|==|!=|<=|>=|<|>)\s*[A-Za-z0-9.*+!_-]+\s*)*,?$/;
256
+
257
+ /**
258
+ * PURE. One PEP 508 requirement split into its IDENTITY (normalised name, sorted extras, marker) and
259
+ * its version SPECIFIER — or null when it is not a plain name requirement (a URL `@`, a path, the old
260
+ * parenthesised form). Only the specifier may differ for a change to read as a pin.
261
+ */
262
+ function parseRequirement(text) {
263
+ const s = String(text).trim();
264
+ const semi = s.indexOf(';');
265
+ const head = semi === -1 ? s : s.slice(0, semi);
266
+ // Whitespace outside quoted values is insignificant in a marker; inside one it is data.
267
+ const marker = semi === -1 ? '' : s.slice(semi + 1).split(/("[^"]*"|'[^']*')/)
268
+ .map((part, i) => (i % 2 ? part : part.replace(/\s+/g, ''))).join('');
269
+ if (head.includes('@')) return null;
270
+ const m = /^([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)\s*(?:\[([^\]]*)\])?\s*(.*)$/.exec(head.trim());
271
+ if (!m) return null;
272
+ const spec = m[3].replace(/\s+/g, '');
273
+ if (spec && !SPEC_RE.test(spec)) return null;
274
+ const name = m[1].toLowerCase().replace(/[-_.]+/g, '-');
275
+ const extras = (m[2] || '').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean).sort().join(',');
276
+ return { name, identity: `${name}[${extras}];${marker}`, spec: spec.replace(/,$/, '') };
277
+ }
278
+
279
+ /** A requirements-format file as `{skeleton: [...], reqs: [{name, spec}]}`: comment, blank and
280
+ * `--hash` stripped; each requirement line reduced to its identity; every other line kept verbatim
281
+ * (whitespace-collapsed), so an option line or an unparseable requirement must match exactly. */
282
+ function requirementsShape(text) {
283
+ const skeleton = [];
284
+ const reqs = [];
285
+ for (const raw of String(text).replace(/\\\r?\n/g, ' ').split(/\r?\n/)) {
286
+ const line = raw.replace(/(^|\s)#.*$/, '').replace(/\s+/g, ' ').trim();
287
+ if (!line) continue;
288
+ if (line.startsWith('-')) { skeleton.push(`opt ${line}`); continue; }
289
+ const bare = line.replace(/\s--hash(?:=|\s+)\S+/g, '').trim();
290
+ const r = parseRequirement(bare);
291
+ if (!r) { skeleton.push(`raw ${line}`); continue; }
292
+ skeleton.push(`req ${r.identity}`);
293
+ reqs.push({ name: r.name, spec: r.spec });
294
+ }
295
+ return { skeleton, reqs };
296
+ }
297
+
298
+ /** Is this `pyproject.toml` array (key `key` in table `table`) a dependency list pip installs from? */
299
+ function isDependencyArray(table, key) {
300
+ const k = key.replace(/^["']|["']$/g, '');
301
+ return (table === 'project' && k === 'dependencies')
302
+ || table === 'project.optional-dependencies'
303
+ || table === 'dependency-groups'
304
+ || (table === 'build-system' && k === 'requires');
305
+ }
306
+
307
+ const TOML_STRING = /"((?:[^"\\]|\\.)*)"|'([^']*)'/g;
308
+
309
+ /** A `pyproject.toml` as `{skeleton, reqs}`: every line verbatim, except that inside a dependency array
310
+ * each requirement string is reduced to its identity. */
311
+ function pyprojectShape(text) {
312
+ const skeleton = [];
313
+ const reqs = [];
314
+ let table = '';
315
+ let depth = 0; // bracket depth of the dependency array we are inside; 0 = not in one
316
+ for (const line of String(text).split(/\r?\n/)) {
317
+ const bare = line.replace(TOML_STRING, '""');
318
+ if (!depth) {
319
+ const sec = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/.exec(line);
320
+ if (sec) { table = sec[1].replace(/\s+/g, ''); skeleton.push(line); continue; }
321
+ const kv = /^\s*("[^"]*"|'[^']*'|[A-Za-z0-9_.-]+)\s*=\s*\[/.exec(line);
322
+ if (!kv || !isDependencyArray(table, kv[1])) { skeleton.push(line); continue; }
323
+ }
324
+ depth += (bare.match(/\[/g) || []).length - (bare.match(/\]/g) || []).length;
325
+ if (depth < 0) depth = 0;
326
+ skeleton.push(line.replace(TOML_STRING, (all, dq, sq) => {
327
+ const r = parseRequirement(dq !== undefined ? dq : sq);
328
+ if (!r) return all;
329
+ reqs.push({ name: r.name, spec: r.spec });
330
+ return `<${r.identity}>`;
331
+ }));
332
+ }
333
+ return { skeleton, reqs };
334
+ }
335
+
336
+ /**
337
+ * PURE (#476). Whether a Python manifest change is PIN-ONLY. Returns `{pins: [names]}` — the
338
+ * requirements whose specifier changed — when both sides are present, the shapes match line for
339
+ * line and at least one specifier differs; else null. `setup.py`/`setup.cfg` → always null.
340
+ */
341
+ function pythonPinChange(filePath, baseText, headText) {
342
+ if (baseText === ABSENT || headText === ABSENT || baseText === null || headText === null) return null;
343
+ const base = filePath.slice(filePath.lastIndexOf('/') + 1);
344
+ if (base === 'setup.py' || base === 'setup.cfg') return null;
345
+ const shape = base === 'pyproject.toml' ? pyprojectShape : requirementsShape;
346
+ const a = shape(baseText);
347
+ const b = shape(headText);
348
+ if (a.skeleton.length !== b.skeleton.length || a.skeleton.some((l, i) => l !== b.skeleton[i])) return null;
349
+ const pins = [];
350
+ for (let i = 0; i < a.reqs.length; i += 1) if (a.reqs[i].spec !== b.reqs[i].spec) pins.push(b.reqs[i].name);
351
+ return pins.length ? { pins } : null;
352
+ }
353
+
190
354
  /** One side's text for a raw-diff entry: `ABSENT`, the blob text, or null on a failed read. */
191
355
  function sideText(git, repo, sha) {
192
356
  if (!sha || ZERO_SHA.test(sha)) return ABSENT;
@@ -197,35 +361,57 @@ function sideText(git, repo, sha) {
197
361
  /**
198
362
  * The diff signals for one branch against trunk, over the merge-base range (`trunk...branch` — the
199
363
  * same tree a squash lands). Returns `{ ok, reason, workflowsTouched, manifestScriptsTouched,
200
- * manifestPaths, pythonManifestTouched, pythonManifestPaths }` (the last two: condition 6, #377): `ok:false` with both flags `null` when the diff itself could not be read;
201
- * `manifestScriptsTouched` `true`/`false`/`null` (unmeasurable), with `manifestPaths` listing every
202
- * manifest whose scripts changed. Never throws.
364
+ * manifestPaths, manifestScriptsAddOnly, pythonManifestTouched, pythonManifestPaths, pythonPinOnly }`
365
+ * (the Python pair: condition 6, #377): `ok:false` with every flag `null` when the diff itself could
366
+ * not be read; `manifestScriptsTouched` `true`/`false`/`null` (unmeasurable), with `manifestPaths`
367
+ * listing every manifest whose scripts changed. `manifestScriptsAddOnly` (#475) and `pythonPinOnly`
368
+ * (#476): `[]` when their condition is untouched, `[{path, added|pins}]` when EVERY touched manifest
369
+ * is of the admissible shape, `null` otherwise. Never throws.
203
370
  */
204
371
  function cureDiffSignals(git, repo, trunk, branch) {
205
372
  const raw = git.git(['diff', '-z', '--no-renames', '--raw', '--no-abbrev', `${trunk}...${branch}`], repo);
206
373
  if (!raw.ok) {
207
374
  return { ok: false, reason: `git diff ${trunk}...${branch} failed: ${(raw.stderr || '').split('\n')[0] || raw.code}`,
208
- workflowsTouched: null, manifestScriptsTouched: null, manifestPaths: [],
209
- pythonManifestTouched: null, pythonManifestPaths: [] };
375
+ workflowsTouched: null, manifestScriptsTouched: null, manifestPaths: [], manifestScriptsAddOnly: null,
376
+ pythonManifestTouched: null, pythonManifestPaths: [], pythonPinOnly: null };
210
377
  }
211
378
  const entries = parseRaw(raw.stdout);
212
379
  const workflowsTouched = entries.some((e) => e.path.startsWith('.github/workflows/'));
213
380
 
214
381
  const touched = [];
215
382
  const unmeasured = [];
383
+ let additions = [];
216
384
  for (const e of entries) {
217
385
  if (!isManifest(e.path)) continue;
218
386
  if (!FILE_MODES.has(e.oldMode) || !FILE_MODES.has(e.newMode)) { unmeasured.push(e.path); continue; }
219
387
  if (e.oldSha && e.oldSha === e.newSha) continue; // mode-only change: same content
220
- const differs = scriptsBlockDiffers(sideText(git, repo, e.oldSha), sideText(git, repo, e.newSha));
221
- if (differs === true) touched.push(e.path);
222
- else if (differs === null) unmeasured.push(e.path);
388
+ const before = sideText(git, repo, e.oldSha);
389
+ const after = sideText(git, repo, e.newSha);
390
+ const differs = scriptsBlockDiffers(before, after);
391
+ if (differs === true) {
392
+ touched.push(e.path);
393
+ const add = additions && scriptsAddition(before, after);
394
+ additions = add ? additions.concat([{ path: e.path, added: add.added }]) : null;
395
+ } else if (differs === null) unmeasured.push(e.path);
223
396
  }
224
397
  let manifestScriptsTouched = false;
225
398
  if (touched.length) manifestScriptsTouched = true;
226
399
  else if (unmeasured.length) manifestScriptsTouched = null;
227
400
 
228
401
  const py = pythonSignal(git, repo, trunk, branch, entries);
402
+ // #476: whether every touched Python manifest changed only a version specifier. Read only when
403
+ // condition 6 actually fires, so an ordinary diff pays nothing for it.
404
+ let pins = py.touched === true ? [] : (py.touched === false ? [] : null);
405
+ if (py.touched === true) {
406
+ const byPath = new Map(entries.map((e) => [e.path, e]));
407
+ for (const p of py.paths) {
408
+ const e = byPath.get(p);
409
+ const pin = e && FILE_MODES.has(e.oldMode) && FILE_MODES.has(e.newMode)
410
+ && pythonPinChange(p, sideText(git, repo, e.oldSha), sideText(git, repo, e.newSha));
411
+ if (!pin) { pins = null; break; }
412
+ pins.push({ path: p, pins: pin.pins });
413
+ }
414
+ }
229
415
  const reasons = [];
230
416
  if (unmeasured.length && !touched.length) reasons.push(`could not read the scripts of: ${unmeasured.join(', ')}`);
231
417
  if (py.touched === null) reasons.push(py.reason);
@@ -233,7 +419,9 @@ function cureDiffSignals(git, repo, trunk, branch) {
233
419
  ok: true,
234
420
  reason: reasons.join('; '),
235
421
  workflowsTouched, manifestScriptsTouched, manifestPaths: touched,
422
+ manifestScriptsAddOnly: manifestScriptsTouched === false ? [] : (manifestScriptsTouched === true ? additions : null),
236
423
  pythonManifestTouched: py.touched, pythonManifestPaths: py.paths,
424
+ pythonPinOnly: pins,
237
425
  };
238
426
  }
239
427
 
@@ -264,4 +452,5 @@ function pythonSignal(git, repo, trunk, branch, entries) {
264
452
  return { touched: paths.length > 0, paths, reason: '' };
265
453
  }
266
454
 
267
- module.exports = { cureDiffSignals, scriptsBlockDiffers, isPythonManifest, pythonIncludes, ABSENT };
455
+ module.exports = { cureDiffSignals, scriptsBlockDiffers, scriptsAddition, pythonPinChange, parseRequirement,
456
+ isPythonManifest, pythonIncludes, ABSENT };
@@ -49,20 +49,14 @@
49
49
  * costs one line in tools/colab — flagged, not decided, by this module.
50
50
  */
51
51
 
52
- /** The two comment markers. STABLE WIRE FORMAT — do not reword casually; `tools/colab` and any
53
- * vendored reader parse these verbatim, the same posture as GRANT_MARK/REVOKE_MARK. */
54
- const DECISION_MARK = '⚖ Decision recorded';
55
- const REOPEN_MARK = '↩ Decision reopened';
56
-
57
- // Deliberately DIFFERENT leading glyph (not just different trailing text) — mirrors
58
- // migration-grant.js's GRANT_RE/REVOKE_RE split, and for the identical reason: a reopen mark
59
- // that merely suffixed the decision mark would make every reopen parse as a fresh decision,
60
- // silently reopening exactly the door it was posted to close.
61
- const DECISION_RE = /^⚖ Decision recorded — ruled-by `([^`]*)` · answers `([^`]*)` · host `([^`]*)` · (\S+)/;
62
- const REOPEN_RE = /^↩ Decision reopened — ruled-by `([^`]*)` · host `([^`]*)` · (\S+)/;
52
+ // The wire format — both marks (different leading glyphs, so a reopen never parses as a fresh
53
+ // decision), both regexes, and the encode/decode pairs — lives in codec/decision.js (#498, epic
54
+ // #496). Re-exported below under the names this module always had.
55
+ const codec = require('./codec/decision');
56
+ const { DECISION_MARK, REOPEN_MARK, DECISION_RE, REOPEN_RE } = codec;
63
57
 
64
58
  /**
65
- * The exact decision-comment body. Keep in lockstep with DECISION_RE.
59
+ * The exact decision-comment body (codec `encodeDecision`).
66
60
  * `ruledBy` names the human whose call it is — never the typist (mirrors `Filed-by:`).
67
61
  * `answers` is the `<!-- decision:options -->` block reference this decision resolves
68
62
  * (a comment URL/id), or `-` when there was no options block to answer.
@@ -70,16 +64,13 @@ const REOPEN_RE = /^↩ Decision reopened — ruled-by `([^`]*)` · host `([^`]*
70
64
  * what was rejected (CONVENTIONS.md §5, design conclusions' Unit 1).
71
65
  */
72
66
  function decisionCommentBody(ruledBy, answers, host, iso, body) {
73
- const head = `${DECISION_MARK} — ruled-by \`${ruledBy}\` · answers \`${answers || '-'}\` · host \`${host}\` · ${iso}`;
74
- return body ? `${head}\n\n${body}` : head;
67
+ return codec.encodeDecision({ ruledBy, answers, host, at: iso, body: body || null });
75
68
  }
76
69
 
77
- /** The exact reopen-comment body. Keep in lockstep with REOPEN_RE. Reopening is NOT scoped to
78
- * the same `ruledBy` — see liveDecisions doc below for why. */
70
+ /** The exact reopen-comment body (codec `encodeReopen`). Reopening is NOT scoped to the same
71
+ * `ruledBy` — see liveDecisions doc below for why. */
79
72
  function reopenCommentBody(ruledBy, host, iso, reason) {
80
- const head = `${REOPEN_MARK} — ruled-by \`${ruledBy}\` · host \`${host}\` · ${iso}`
81
- + ' — every decision on this issue up to this point is superseded.';
82
- return reason ? `${head}\n\n${reason}` : head;
73
+ return codec.encodeReopen({ ruledBy, host, at: iso, body: reason || null });
83
74
  }
84
75
 
85
76
  /**
@@ -163,26 +154,11 @@ function answeredOptionRefs(comments, trust) {
163
154
  .map((d) => d.answers);
164
155
  }
165
156
 
166
- /** The question-side marker (CONVENTIONS.md §5, *Decision options*, #126). Only its PRESENCE
167
- * and its comment's createdAt matter here — the block's content is parsed by consumers. */
168
- const OPTIONS_RE = /<!--\s*decision:options\b/;
169
-
170
- /** The design-approval ask (CONVENTIONS.md §5, *Decision options*, #379): the second
171
- * machine-readable question shape, beside the options block. A design issue whose finished
172
- * artifact awaits approval carries `Mockup: <url of the frozen image>` in its BODY, anchored at
173
- * the start of a line — never a comment, so a reader finds it with one field and no timeline.
174
- * A set reviewed together carries one line in each member's body; the review comment keeps the
175
- * full gallery. Leading whitespace disqualifies the line on purpose: an indented `Mockup:` is
176
- * quoted or nested text, not the filer's declaration. */
177
- const MOCKUP_RE = /^Mockup:[ \t]*(\S+)[ \t]*$/gm;
178
-
179
- /** Every `Mockup:` URL declared in an issue body, in order. Empty when none (or no body). */
180
- function mockupUrls(body) {
181
- if (typeof body !== 'string' || body === '') return [];
182
- const out = [];
183
- for (const m of body.replace(/\r\n/g, '\n').matchAll(MOCKUP_RE)) out.push(m[1]);
184
- return out;
185
- }
157
+ /** The question-side marker (CONVENTIONS.md §5, *Decision options*, #126) and the
158
+ * design-approval `Mockup:` body line (#379) — both now in codec/decision.js (#498). Only the
159
+ * options block's PRESENCE and its comment's createdAt matter here; a `Mockup:` line counts only
160
+ * at the start of a body line (an indented one is quoted text, not the filer's declaration). */
161
+ const { OPTIONS_RE, MOCKUP_RE, mockupUrls } = codec;
186
162
 
187
163
  const ASK_SHAPES = Object.freeze({ OPTIONS: 'options', MOCKUP: 'mockup' });
188
164
 
@@ -21,6 +21,13 @@ const DOCS_DIR = 'docs/';
21
21
  const NEVER_BASENAMES = Object.freeze(['CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md']);
22
22
  /** Config directories: nothing under them is documentation, at any depth. */
23
23
  const NEVER_DIRS = Object.freeze(['.claude', '.github', '.githooks']);
24
+ /**
25
+ * Agent-instruction directories named by more than one segment (#520): nothing under them is
26
+ * documentation, at any depth. `.colab/skills/<skill>.md` is a skill's local policy — text an agent
27
+ * loads and follows over the skill's own — so one `.md` there changes agent behaviour exactly as a
28
+ * `CLAUDE.md` does. Only this subtree: the rest of `.colab/` is judged by the ordinary rules.
29
+ */
30
+ const NEVER_SUBDIRS = Object.freeze(['.colab/skills']);
24
31
 
25
32
  const MODE_SYMLINK = '120000';
26
33
  const MODE_GITLINK = '160000';
@@ -35,6 +42,13 @@ function pathReason(p) {
35
42
  if (NEVER_BASENAMES.includes(base)) return `${base} is agent rules, not documentation`;
36
43
  const dir = segs.slice(0, -1).find((s) => NEVER_DIRS.includes(s));
37
44
  if (dir) return `under ${dir}/ (config)`;
45
+ const dirs = segs.slice(0, -1);
46
+ for (const sub of NEVER_SUBDIRS) {
47
+ const want = sub.split('/');
48
+ for (let i = 0; i + want.length <= dirs.length; i++) {
49
+ if (want.every((w, j) => dirs[i + j] === w)) return `under ${sub}/ (skill local policy — agent instructions)`;
50
+ }
51
+ }
38
52
  if (String(p).startsWith(DOCS_DIR)) return null;
39
53
  const dot = base.lastIndexOf('.');
40
54
  const ext = dot > 0 ? base.slice(dot) : '';
@@ -151,6 +165,6 @@ function directChanges(git, repo, trunk, since) {
151
165
  }
152
166
 
153
167
  module.exports = {
154
- DOC_EXTENSIONS, DOCS_DIR, NEVER_BASENAMES, NEVER_DIRS,
168
+ DOC_EXTENSIONS, DOCS_DIR, NEVER_BASENAMES, NEVER_DIRS, NEVER_SUBDIRS,
155
169
  pathReason, classify, parseRaw, parseBinary, branchChanges, directChanges,
156
170
  };
@@ -53,7 +53,8 @@
53
53
  * Context shape both sides build (identically named, audit.mjs and adopt.js each computing the
54
54
  * booleans from their own sources — a real git checkout for one, a `git status`-aware `io` for
55
55
  * the other):
56
- * { trunk, hasProduction, deploy, hasDeployWorkflow, hasRunbook, deployWorkflowNames? }
56
+ * { trunk, hasProduction, deploy, hasDeployWorkflow, hasRunbook, deployWorkflowNames?, branches? }
57
+ * `branches` (#522) is what `singleTrunkViolation` reads — omitting it fails closed to trunk "main".
57
58
  * `deployWorkflowNames` is OPTIONAL and cosmetic only (the `none` violation names which
58
59
  * workflow(s) contradict it) — omitting it (as adopt.js's ctx does) only drops the parenthetical
59
60
  * from the message, never changes which entries fire.
@@ -74,13 +75,45 @@ function evaluateExposure(exposure, ctx) {
74
75
  }
75
76
  }
76
77
 
78
+ /**
79
+ * #522: the single-trunk invariant shared by every shape with no release branch — `exposure: none`,
80
+ * `exposure: released` with `production: null`, and the legacy `tier: B` (audit/audit.mjs). It is
81
+ * about HOW MANY long-lived branches exist, never how the one branch is spelled: an existing repo
82
+ * whose default branch is `master` (or anything else) adopts as-is, with nothing renamed.
83
+ *
84
+ * What it refuses is the two-branch shape wearing a single-trunk label: a `main` branch sitting
85
+ * beside a trunk that is not `main` is the live/released split (main = what ships, trunk = where
86
+ * sessions land), and declaring "nothing consumes this" over it would hide the release branch.
87
+ *
88
+ * `branches` — every branch name the caller can see (local ∪ remote-tracking), or null/undefined
89
+ * when it cannot list them. Unknown FAILS CLOSED to the old spelling rule (trunk "main"): a
90
+ * non-main trunk is accepted only when a readable branch list proves no `main` sits beside it.
91
+ *
92
+ * Returns null when the invariant holds, else the reason text (no prefix — each caller names its
93
+ * own shape in front of it).
94
+ */
95
+ function singleTrunkViolation(trunk, branches) {
96
+ if (!trunk) return `no trunk declared, found ${JSON.stringify(trunk)}`;
97
+ if (trunk === 'main') return null;
98
+ if (!Array.isArray(branches)) {
99
+ return `trunk ${JSON.stringify(trunk)} can stand in for "main" only when the branch list is readable `
100
+ + 'and shows no "main" beside it, and the branch list could not be read';
101
+ }
102
+ if (branches.includes('main')) {
103
+ return `trunk is ${JSON.stringify(trunk)} and a "main" branch exists beside it — that is the `
104
+ + 'two-branch (live/released) shape, not a single trunk';
105
+ }
106
+ return null;
107
+ }
108
+
77
109
  function evaluateNone(ctx) {
78
110
  const out = [];
79
- if (ctx.trunk !== 'main') {
111
+ const single = singleTrunkViolation(ctx.trunk, ctx.branches);
112
+ if (single) {
80
113
  out.push({
81
114
  kind: 'fail',
82
- message: `exposure: none requires trunk "main", found ${JSON.stringify(ctx.trunk)} — nothing `
83
- + 'consumes this repo, so there is no release branch to speak of',
115
+ message: `exposure: none requires a single trunk — ${single} — nothing consumes this repo, `
116
+ + 'so there is no release branch to speak of',
84
117
  });
85
118
  }
86
119
  if (ctx.hasDeployWorkflow) {
@@ -131,11 +164,12 @@ function evaluateLive(ctx) {
131
164
 
132
165
  function evaluateReleasedNoProduction(ctx) {
133
166
  const out = [];
134
- if (ctx.trunk !== 'main') {
167
+ const single = singleTrunkViolation(ctx.trunk, ctx.branches);
168
+ if (single) {
135
169
  out.push({
136
170
  kind: 'fail',
137
- message: `exposure: released with production: null requires trunk "main", found `
138
- + `${JSON.stringify(ctx.trunk)} — nothing is live, so there is no release branch to speak of`,
171
+ message: `exposure: released with production: null requires a single trunk — ${single} — `
172
+ + 'nothing is live, so there is no release branch to speak of',
139
173
  });
140
174
  }
141
175
  if (ctx.deploy !== null && ctx.deploy !== undefined && ctx.deploy !== 'none') {
@@ -204,4 +238,4 @@ function evaluateReleasedWithProduction(ctx) {
204
238
  return out;
205
239
  }
206
240
 
207
- module.exports = { evaluateExposure };
241
+ module.exports = { evaluateExposure, singleTrunkViolation };