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

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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +309 -3
  3. package/README.vi.md +279 -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 +117 -0
  22. package/templates/release-auto.yml +470 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13746 -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-cut.js +822 -0
  73. package/tools/lib/release-finalize.js +481 -0
  74. package/tools/lib/release-policy.js +358 -0
  75. package/tools/lib/release-tag.js +225 -0
  76. package/tools/lib/ship-batch.js +277 -0
  77. package/tools/lib/ship-roles.js +71 -0
  78. package/tools/lib/ship-target-sync.js +181 -0
  79. package/tools/lib/shipguard.js +317 -0
  80. package/tools/lib/shipped-branch.js +56 -0
  81. package/tools/lib/solo.js +213 -0
  82. package/tools/lib/squash.js +515 -0
  83. package/tools/lib/stale-base.js +70 -0
  84. package/tools/lib/stamp.js +703 -0
  85. package/tools/lib/state.js +262 -0
  86. package/tools/lib/teardown.js +83 -0
  87. package/tools/lib/trust-humans.js +104 -0
  88. package/tools/lib/util.js +98 -0
  89. package/tools/lib/wake.js +188 -0
  90. package/tools/lib/workflow-triggers.js +273 -0
  91. package/tools/lib/writes-authority.js +237 -0
  92. package/tools/lib/yaml.js +101 -0
  93. package/bin/cli.js +0 -3
@@ -0,0 +1,703 @@
1
+ 'use strict';
2
+ /**
3
+ * Stamp + drift logic, shared by `audit/audit.mjs` (report) and `colab update` (report + refresh).
4
+ *
5
+ * Copy-and-own means nothing is pushed to an adopter: a copied artifact carries a STAMP naming
6
+ * the template and the handbook version it came from, and drift is discovered by comparing that
7
+ * stamp against the handbook's own git history. Both tools must read stamps identically — a
8
+ * second implementation that disagreed about what "behind" means is exactly the two-places-drift
9
+ * disease this handbook exists to kill, so the reading lives here once.
10
+ *
11
+ * CommonJS on purpose: `tools/colab` is CJS, `audit/audit.mjs` is ESM. CJS is the format both can
12
+ * consume (the audit pulls it in through `createRequire`); the reverse is not true from a
13
+ * synchronous CLI.
14
+ *
15
+ * Every function takes the handbook root explicitly rather than resolving it — the two callers
16
+ * locate the handbook differently (the audit honours COLAB_HANDBOOK; the CLI walks up from its
17
+ * own file), and a module that guessed would be wrong for one of them.
18
+ */
19
+
20
+ const { execFileSync } = require('child_process');
21
+ const releaseTag = require('./release-tag.js');
22
+
23
+ // The artifact kinds that carry a stamp. Workflow copies are WHOLE-FILE copies, so a pristine one
24
+ // can be regenerated byte-for-byte. The CLAUDE block is a fragment pasted into a larger file whose
25
+ // placeholders the adopter fills in — see CLAUDE_BLOCK below.
26
+ const CLAUDE_BLOCK_TEMPLATE = 'templates/repo-CLAUDE-block.md';
27
+
28
+ // The FROZEN CLI copy: `install.sh --tools` copies `tools/colab` + `tools/lib/` into
29
+ // `<COLAB_HOME>/bin/` and writes the stamp beside it, so a long-lived process never resolves the
30
+ // CLI through a working tree. The symlink install (`~/.local/bin/colab`) is deliberately the
31
+ // opposite — a human session should follow whatever branch the handbook clone has checked out —
32
+ // but an always-on service must not change behaviour because somebody checked out an unrelated
33
+ // branch. Refreshing the frozen copy is therefore an act (re-run install.sh), never a side effect.
34
+ //
35
+ // The stamp is a SIDECAR file rather than a line prepended into the script: `colab` is executable
36
+ // with a shebang on line 1, and the sidecar keeps the copied bytes identical to the source.
37
+ // It uses the ordinary workflow stamp convention (`# colab-handbook: <name> @ <version>`) and is
38
+ // read with parseWorkflowStamp, so there is one stamp format on the machine, not two.
39
+ const FROZEN_STAMP_NAME = 'colab-bin';
40
+ const FROZEN_STAMP_FILE = 'STAMP';
41
+
42
+ /**
43
+ * The handbook version at/after which #144's authority-flip advisory activates: a `warn`,
44
+ * on a repo whose axis of record is a LEGACY `tier` read (no `exposure` declared), noting
45
+ * that `tier` is now read as legacy rather than authoritative. Dormant below this version,
46
+ * mirroring the `hb.untagged` precedent `compareStamp` already uses (deactivated while there
47
+ * is no real version line to compare against) — the re-keying itself is NOT gated by it (it
48
+ * is designed to be output-identical on every descriptor without `exposure` regardless of
49
+ * handbook version; only this one new warn is).
50
+ *
51
+ * No tag exists past the axis commits yet (#200, a human act, still pending) — the handbook
52
+ * is expected to cut a MINOR tag containing #144 next (keeping `v1.x`, so the fleet gets a
53
+ * clean baseline first), and only a LATER, separate major bump would ever reach this
54
+ * constant. Comparison uses `cmpSemver`, so a same-or-later `v2.x.y` also arms it.
55
+ */
56
+ const AUTHORITY_FLIP_VERSION = 'v2.0.0';
57
+ // What the frozen copy is made of, as repo-relative paths — the same role `templateFiles()` plays
58
+ // for a template, and fed to the same `git log <stamp>..HEAD -- <paths>` question.
59
+ // Every path install.sh's freeze_cli COPIES belongs here: a source it copies but this list omits can
60
+ // change without ever marking a frozen copy behind. tools/package.json was exactly that gap (#341) —
61
+ // an `engines` bump shipped to no machine. tools/lib/install-sh.test.js holds the two lists together.
62
+ const FROZEN_SOURCES = ['tools/colab', 'tools/lib', 'tools/package.json'];
63
+
64
+ // ---------------------------------------------------------------------------
65
+ // git access to the handbook checkout
66
+ // ---------------------------------------------------------------------------
67
+
68
+ function gitIn(root, args) {
69
+ try {
70
+ return {
71
+ ok: true,
72
+ out: execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(),
73
+ };
74
+ } catch (_) {
75
+ return { ok: false, out: '' };
76
+ }
77
+ }
78
+
79
+ /** `version` of `<root>/package.json` when this root is a published package (not a git checkout), else null. */
80
+ function packageVersion(root) {
81
+ try {
82
+ const j = JSON.parse(require('fs').readFileSync(require('path').join(root, 'package.json'), 'utf8'));
83
+ return typeof j.version === 'string' && /^\d+\.\d+\.\d+$/.test(j.version) ? j.version : null;
84
+ } catch (_) {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ /**
90
+ * The handbook's own identity: { root, hasGit, untagged, version }.
91
+ * Before the first tag exists the version is 'v0' and `untagged` is true, which DEACTIVATES stamp
92
+ * comparison in both callers — there is no real version line to compare against, and inventing one
93
+ * would mark every adopter stale against a version that never shipped.
94
+ *
95
+ * `git -C <root> rev-parse --show-toplevel` does not fail when `root` itself has no `.git` — it
96
+ * walks UP and answers about the nearest ENCLOSING repository. So a root that is not itself a repo
97
+ * still returns `ok`, and treating success alone as "hasGit: true" reports the wrong repo's tags
98
+ * with no error and no advisory (root is a subdirectory that legitimately has no `.git` of its own
99
+ * — e.g. working trees file-synced between machines while git metadata deliberately is not, nested
100
+ * inside a parent that IS a repo). The fix is the comparison this function was missing: the
101
+ * toplevel git actually found must equal `root` itself, not merely exist. realPath both sides —
102
+ * `--show-toplevel` resolves symlinks, so a symlinked root would otherwise never match its own
103
+ * unresolved spelling (same reasoning as `realPath` above, applied here for the same failure mode).
104
+ */
105
+ function handbookInfo(root) {
106
+ const top = gitIn(root, ['rev-parse', '--show-toplevel']);
107
+ if (!top.ok || realPath(top.out) !== realPath(require('path').resolve(root))) {
108
+ // An npm install (#431) has no git of its own: the registry copy's version is its package.json,
109
+ // which the publish job stamps from the release tag. Without this a copy installed from the
110
+ // registry would stamp every adopter's files `v0`.
111
+ const pkgVersion = packageVersion(root);
112
+ if (pkgVersion) return { root, hasGit: false, untagged: false, version: `v${pkgVersion}` };
113
+ return { root, hasGit: false, untagged: true, version: 'v0' };
114
+ }
115
+ // Pre-release tags are not a version (#334): a candidate must never become what adopters are
116
+ // compared against or stamped with. Only candidates, no final yet, reads as untagged.
117
+ const tag = releaseTag.latestReleaseTag(root);
118
+ if (!tag) return { root, hasGit: true, untagged: true, version: 'v0' };
119
+ return { root, hasGit: true, untagged: false, version: tag };
120
+ }
121
+
122
+ /**
123
+ * What to stamp a frozen copy WITH: { version, tag, exact, untagged }.
124
+ *
125
+ * A frozen copy is bytes taken from a working tree, and when that tree is ahead of the last tag no
126
+ * version honestly describes it. Stamping the bare tag overstates what the copy contains — it
127
+ * silently claims to be a release it is newer than. So `version` is `git describe --tags` (pre-release
128
+ * tags excluded — release-tag.js, #334), which
129
+ * is the bare tag when HEAD sits exactly on one (`v1.6.1`, the common case, unchanged) and the long
130
+ * form when it does not (`v1.6.1-14-gc8436c6`).
131
+ *
132
+ * The long form is not a cosmetic label — it is chosen because it stays correct everywhere the
133
+ * stamp is already consumed, with no second format on the machine:
134
+ * - parseWorkflowStamp's version pattern accepts it;
135
+ * - cmpSemver reads it as its tag (trailing junk parses to 0), so it never trips the "stamp is
136
+ * NEWER than the handbook" branch against its own tag;
137
+ * - `git rev-parse` resolves it, so classifyFrozen can use it as a lower bound directly — which
138
+ * makes the comparison EXACT rather than merely honest: a copy frozen mid-cycle is measured
139
+ * from the commit it was actually taken from, so the next release marks it behind only for the
140
+ * commits it genuinely lacks.
141
+ *
142
+ * Dirty trees are deliberately NOT described (`--dirty` would produce a ref nothing can resolve,
143
+ * turning every such copy into `n-a` with misleading "fetch tags" advice). Uncommitted work in a
144
+ * frozen copy stays outside this model.
145
+ */
146
+ function freezeVersion(root) {
147
+ const hb = handbookInfo(root);
148
+ if (hb.untagged || !hb.hasGit) return { version: 'v0', tag: 'v0', exact: false, untagged: true };
149
+ // Long form measured from the last FINAL tag (#334) — a tree sitting on `v1.3.0-rc.1` stamps
150
+ // `v1.2.0-N-g<sha>`, never the candidate.
151
+ const d = gitIn(root, releaseTag.describeArgs({ abbrev: null }));
152
+ const version = d.ok && d.out ? d.out : hb.version;
153
+ return { version, tag: hb.version, exact: version === hb.version, untagged: false };
154
+ }
155
+
156
+ /**
157
+ * The handbook's shared git directory — the one identity that survives worktrees. Every worktree
158
+ * of a repo reports the SAME `--git-common-dir`, while their working-tree paths all differ.
159
+ */
160
+ function gitCommonDir(root) {
161
+ const r = gitIn(root, ['rev-parse', '--git-common-dir']);
162
+ if (!r.ok || !r.out) return null;
163
+ return realPath(require('path').resolve(root, r.out));
164
+ }
165
+
166
+ /**
167
+ * Resolve symlinks before comparing paths, falling back to the input when the path does not exist.
168
+ *
169
+ * Not optional pedantry: git answers `--git-common-dir` RELATIVELY from a main checkout (`.git`)
170
+ * but ABSOLUTELY, and already symlink-resolved, from a worktree. So the two sides of the comparison
171
+ * arrive in different forms, and any handbook checkout reached through a symlinked path (`/tmp` on
172
+ * macOS, a symlinked home, a network mount) produced two different strings for one directory —
173
+ * making the repo fail to recognise itself.
174
+ */
175
+ function realPath(p) {
176
+ try { return require('fs').realpathSync(p); } catch (_) { return p; }
177
+ }
178
+
179
+ /**
180
+ * Is `repoPath` the handbook itself? Both tools must answer this identically, so it is answered
181
+ * ONCE, here — the same reason stamp reading lives here.
182
+ *
183
+ * NOT a path-string comparison, and that is the whole point. `colab update` used to test
184
+ * `abs === handbookRoot`, which silently answers "no" whenever the CLI runs from a git WORKTREE of
185
+ * the handbook: the CLI locates its root by walking up from its own file (giving the worktree),
186
+ * while the fleet registry names the main checkout. Same repo, two spellings, and the handbook was
187
+ * audited as its own consumer — reported `unstamped`, with advice to stamp its own CLAUDE.md as a
188
+ * copy of a version of itself. Comparing git common dirs is immune to that: worktree, symlink or
189
+ * a differently-spelled path all resolve to one identity.
190
+ *
191
+ * Remote (owner/name) targets are out of scope: recognising "self" through the API would need the
192
+ * name match this deliberately avoids.
193
+ */
194
+ function isHandbookItself(repoPath, handbookRoot) {
195
+ const { resolve } = require('path');
196
+ if (!repoPath || !handbookRoot) return false;
197
+ const root = realPath(resolve(repoPath));
198
+ if (root === realPath(resolve(handbookRoot))) return true;
199
+ const a = gitCommonDir(root);
200
+ const b = gitCommonDir(handbookRoot);
201
+ return a !== null && b !== null && a === b;
202
+ }
203
+
204
+ /** Template stems present in the handbook (e.g. "ci-node", "ci-laravel", "release-tag"). */
205
+ function templateNames(root) {
206
+ const { readdirSync } = require('fs');
207
+ const { join } = require('path');
208
+ try {
209
+ return new Set(
210
+ readdirSync(join(root, 'templates'))
211
+ .filter((f) => /\.ya?ml$/.test(f))
212
+ .map((f) => f.replace(/\.ya?ml$/, '')),
213
+ );
214
+ } catch (_) {
215
+ return new Set();
216
+ }
217
+ }
218
+
219
+ /** Both spellings a template file may use, as repo-relative paths for `git log`/`git show`. */
220
+ function templateFiles(name) {
221
+ return [`templates/${name}.yml`, `templates/${name}.yaml`];
222
+ }
223
+
224
+ // The trailer key a handbook editor writes on a commit to declare — at edit time, never
225
+ // inferred afterward — that a template change carries no rule content (#272). One key,
226
+ // one truthy spelling; keep this narrow so a reader never has to guess what counts.
227
+ const RULE_NEUTRAL_TRAILER = 'Rule-Neutral';
228
+ const RULE_NEUTRAL_TRUE = /^(yes|true)$/i;
229
+
230
+ /**
231
+ * Is every commit that touched `files` in `sinceRef..untilRef` marked with the
232
+ * Rule-Neutral trailer? Empty range (nothing changed) reads as false — callers only ask
233
+ * this after confirming `changed`, and "no commits" is not the same claim as "all
234
+ * commits declared neutral".
235
+ *
236
+ * Uses `\x1f`/`\x1e` as field/record separators, not the trailer text itself, because
237
+ * `%(trailers:valueonly)` renders empty for a commit with no trailer — a plain newline
238
+ * join cannot tell "no trailer" apart from "trailer, empty value" from the commit count.
239
+ */
240
+ function allCommitsRuleNeutral(root, files, sinceRef, untilRef) {
241
+ const fmt = `%H\x1f%(trailers:key=${RULE_NEUTRAL_TRAILER},valueonly,separator=%x2C)\x1e`;
242
+ const r = gitIn(root, ['log', `--format=${fmt}`, `${sinceRef}..${untilRef}`, '--', ...files]);
243
+ if (!r.ok || !r.out) return false;
244
+ const records = r.out.split('\x1e').map((s) => s.trim()).filter(Boolean);
245
+ if (records.length === 0) return false;
246
+ return records.every((rec) => {
247
+ const value = rec.split('\x1f')[1] || '';
248
+ return RULE_NEUTRAL_TRUE.test(value.trim());
249
+ });
250
+ }
251
+
252
+ /**
253
+ * Did any of the given files change between the stamped version and `untilRef` (default HEAD)?
254
+ * Returns { verifiable, changed, ruleNeutral }. verifiable=false when either ref does not
255
+ * resolve in this checkout (a tag we do not have) — reported, never guessed. `ruleNeutral` is
256
+ * only ever true alongside `changed: true` — see `allCommitsRuleNeutral` above (#272): a
257
+ * template stays a hard fail unless EVERY commit since the stamp was deliberately declared
258
+ * rule-neutral by whoever wrote it, never by comparing before/after content here.
259
+ *
260
+ * This is the check that keeps releases quiet: comparing version STRINGS would mark every adopter
261
+ * stale on every handbook release, including releases that touched nothing they copied.
262
+ *
263
+ * `untilRef` exists because the two callers are asking about different UNITS. A template copy is
264
+ * compared against HEAD: the adopter refreshes from the working tree, so the working tree is the
265
+ * thing they can actually get. The frozen CLI copy is compared against the latest TAG — see
266
+ * classifyFrozen for why measuring it to HEAD made every maintainer's machine permanently stale.
267
+ */
268
+ function templateChangedSince(root, files, sinceRef, untilRef = 'HEAD') {
269
+ const resolves = (ref) => gitIn(root, ['rev-parse', '--verify', '--quiet', ref + '^{commit}']).ok;
270
+ if (!resolves(sinceRef) || !resolves(untilRef)) return { verifiable: false, changed: false, ruleNeutral: false };
271
+ const log = gitIn(root, ['log', '--oneline', `${sinceRef}..${untilRef}`, '--', ...files]);
272
+ const changed = log.ok && log.out.length > 0;
273
+ const ruleNeutral = changed && allCommitsRuleNeutral(root, files, sinceRef, untilRef);
274
+ return { verifiable: true, changed, ruleNeutral };
275
+ }
276
+
277
+ /**
278
+ * A template's content AS OF a given ref (`git show <ref>:templates/<name>.yml`), or null.
279
+ * Divergence detection stands entirely on this: to know whether a copy was hand-edited you must
280
+ * compare it against what it was copied FROM, not against what the template has since become.
281
+ * Comparing against the current template would call every out-of-date copy "hand-edited".
282
+ */
283
+ function templateAt(root, ref, name) {
284
+ for (const f of templateFiles(name)) {
285
+ const r = gitIn(root, ['show', `${ref}:${f}`]);
286
+ if (r.ok) return r.out;
287
+ }
288
+ return null;
289
+ }
290
+
291
+ // The descriptor axes that entered the model after the original tier/trunk/deploy/production/
292
+ // stack fields — each one is a heading in project.schema.md, added the commit it landed.
293
+ const AXES = ['room', 'exposure', 'writes', 'channels'];
294
+
295
+ /**
296
+ * Which of AXES did NOT yet exist in project.schema.md as of `ref` — i.e. which axes this
297
+ * repo's marker predates, if its CLAUDE stamp names `ref` as the handbook version it was last
298
+ * synced against. Reuses the same stamp-comparison shape as templateChangedSince/templateAt:
299
+ * read the schema doc's content AT THAT REF, never at HEAD, because "predates" is a question
300
+ * about what existed at adoption time, not about what the handbook has since become.
301
+ *
302
+ * `verifiable: false` — same posture as an unresolvable stamp elsewhere in this module — means
303
+ * the ref cannot be read at all (an unfetched tag, a version string that isn't a real ref). The
304
+ * caller must stay SILENT in that case, not guess; a repo whose stamp names a ref this checkout
305
+ * cannot resolve is exactly the "look, don't assume" case the rest of the fleet already treats
306
+ * as unknown rather than as broken.
307
+ *
308
+ * A ref that resolves but predates project.schema.md entirely (the file did not exist yet) is
309
+ * read as "every axis is missing" — `git show` fails per-heading-check below, which already
310
+ * degrades to "not found" correctly with no extra branch.
311
+ */
312
+ function axesPredating(root, ref) {
313
+ const resolves = gitIn(root, ['rev-parse', '--verify', '--quiet', ref + '^{commit}']).ok;
314
+ if (!resolves) return { verifiable: false, axes: [] };
315
+ const schema = gitIn(root, ['show', `${ref}:project.schema.md`]);
316
+ const text = schema.ok ? schema.out : '';
317
+ const missing = AXES.filter((axis) => !new RegExp('^###\\s+`' + axis + '`', 'm').test(text));
318
+ return { verifiable: true, axes: missing };
319
+ }
320
+
321
+ // The ruling's own landed vocabulary (project.schema.md, "writes — optional", and
322
+ // CONVENTIONS.md, "Writes"), used as the boundary marker below rather than a hand-picked
323
+ // version number. Distinct from a structural heading (what AXES/axesPredating match) because
324
+ // the `writes` heading itself did not change — only what is written under it did.
325
+ const WRITES_VETO_MARKER = 'two-state VETO';
326
+
327
+ /**
328
+ * #239: did a repo's marker already tell it what ⚖ #233 changed about `writes:`? Same
329
+ * stamp-comparison shape as axesPredating one function above — read project.schema.md AS OF
330
+ * the repo's OWN stamped ref, never at HEAD, because this asks what a sync at THAT time could
331
+ * have told the repo, not what the handbook has since become.
332
+ *
333
+ * Deliberately gated on the ruling's own arrival (`WRITES_VETO_MARKER`'s presence at `ref`),
334
+ * not a version threshold: unlike `AUTHORITY_FLIP_VERSION` near the top of this file — which
335
+ * exists BECAUSE that advisory wanted to wait for a later, separate major bump — #239's own
336
+ * text says this must not be deferred past the very next tag that carries #237. Reading for
337
+ * the change's own landed text sidesteps having to invent a version number for a tag nobody
338
+ * has cut yet (who tags follows CONVENTIONS §6's release rung).
339
+ *
340
+ * `verifiable: false` on the same terms as axesPredating: an unresolvable ref means stay
341
+ * silent, never guess.
342
+ */
343
+ function writesRulingKnownAt(root, ref) {
344
+ const resolves = gitIn(root, ['rev-parse', '--verify', '--quiet', ref + '^{commit}']).ok;
345
+ if (!resolves) return { verifiable: false, known: false };
346
+ const schema = gitIn(root, ['show', `${ref}:project.schema.md`]);
347
+ const text = schema.ok ? schema.out : '';
348
+ return { verifiable: true, known: text.includes(WRITES_VETO_MARKER) };
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // stamps
353
+ // ---------------------------------------------------------------------------
354
+
355
+ /**
356
+ * Which comment syntax a stamp line should use, chosen by the copied file's language — not a
357
+ * single fixed spelling. `#` works for YAML and shell (the original, and still the default for
358
+ * backward compatibility). A `.mjs`/`.js` copy cannot use it: a bare `#` on any line but a `#!`
359
+ * shebang is a JS syntax error (outside a class body, where it means something else entirely), so
360
+ * a stamped JS file needs `//` or it would break the very file it is stamping (#252).
361
+ */
362
+ function stampCommentPrefix(ext) {
363
+ return ext === 'mjs' || ext === 'js' ? '//' : '#';
364
+ }
365
+
366
+ /** The canonical workflow stamp line. `colab template` writes it; `colab update` rewrites it.
367
+ * `commentPrefix` defaults to `#` (unchanged behaviour for every existing *.yml caller) — pass
368
+ * the value from `stampCommentPrefix(ext)` for a non-YAML template. */
369
+ function stampLine(name, version, commentPrefix = '#') {
370
+ return `${commentPrefix} colab-handbook: ${name} @ ${version}\n`;
371
+ }
372
+
373
+ /**
374
+ * Insert a stamp line into a copied template's body.
375
+ *
376
+ * A `*.yml` copy has always taken the stamp prepended at the very top (line 1) — unchanged here.
377
+ * A copy that opens with a `#!` shebang cannot take that: prepending anything above line 1 breaks
378
+ * the shebang, which is exactly the gap `templates/README.md`'s Hooks section documents (#252).
379
+ * So a shebang file gets the stamp on its SECOND line instead — after the first `\n`, shebang
380
+ * intact on line 1 — and everything else is prepended as before.
381
+ */
382
+ function insertStamp(body, line) {
383
+ if (body.startsWith('#!')) {
384
+ const nl = body.indexOf('\n');
385
+ if (nl === -1) return body + '\n' + line; // shebang with no trailing newline — still safe
386
+ return body.slice(0, nl + 1) + line + body.slice(nl + 1);
387
+ }
388
+ return line + body;
389
+ }
390
+
391
+ /** Workflow stamp: `# colab-handbook: <name> @ <version>` or, for a shebang/JS copy, the same
392
+ * shape with `//` (see stampCommentPrefix) — either prefix is accepted wherever it appears in the
393
+ * file, not just on line 1, so a second-line stamp reads back identically to a first-line one. */
394
+ function parseWorkflowStamp(text) {
395
+ if (!text) return null;
396
+ const m = text.match(/(?:#|\/\/)\s*colab-handbook:\s*([A-Za-z0-9._-]+)\s*@\s*(v?[0-9][0-9A-Za-z.\-+]*)/);
397
+ return m ? { name: m[1], version: m[2] } : null;
398
+ }
399
+
400
+ /** CLAUDE-block stamp: `<!-- colab-handbook @ <version> -->`. */
401
+ function parseClaudeStamp(text) {
402
+ if (!text) return null;
403
+ const m = text.match(/<!--\s*colab-handbook\s*@\s*(v?[0-9][0-9A-Za-z.\-+]*)\s*-->/);
404
+ return m ? { version: m[1] } : null;
405
+ }
406
+
407
+ /**
408
+ * Content fingerprints that mark a workflow as a handbook derivative even when someone renamed the
409
+ * file or dropped the stamp.
410
+ *
411
+ * THE ADMISSION TEST, and it is the whole design: *could this string appear in a file nobody copied
412
+ * from us?* If yes, it is not a fingerprint — it is the STACK'S VOCABULARY, and matching on it
413
+ * accuses every repo that happens to use that stack. We shipped two such strings and both misfired
414
+ * on real repos:
415
+ *
416
+ * - `wayfinder:generate` — a framework command, not our text. ANY workflow doing build-time
417
+ * codegen on that framework contains it, whatever its origin. It flagged three hand-written
418
+ * deploy workflows that had never been near a template.
419
+ * - `gitleaks/gitleaks/releases/download` — the upstream release URL. It identifies gitleaks,
420
+ * not us. Two hand-written CI files on this fleet contain it (including this handbook's own),
421
+ * copied from each other rather than from `templates/`.
422
+ *
423
+ * What survives is text WE COINED: the step names in our templates. No upstream tool, framework or
424
+ * generator emits "Resolve toolchain versions"; a file containing it was typed by us or copied from
425
+ * something that was. Each entry is therefore matched as a STEP NAME (`- name: <marker>`), not as a
426
+ * loose substring — so prose that merely mentions the phrase (a comment, a README, this file) does
427
+ * not trip it.
428
+ *
429
+ * `template` attributes the evidence, which is what lets the advice name a real template instead of
430
+ * a `<name>` placeholder the reader has to guess. `null` means the marker is shared by several
431
+ * templates: it still proves derivation, but not FROM WHICH — and the advice must then say so
432
+ * rather than pick one.
433
+ *
434
+ * Precise on purpose: better to miss an unstamped copy than to nag a file we cannot attribute.
435
+ */
436
+ const WORKFLOW_FINGERPRINTS = [
437
+ // Header lines — verbatim template prose, and self-attributing.
438
+ { marker: 'CI (Node) — TEMPLATE. Copy me into your repo', kind: 'text', template: 'ci-node' },
439
+ { marker: 'CI (Laravel) — TEMPLATE. Copy me into your repo', kind: 'text', template: 'ci-laravel' },
440
+ { marker: 'CI (Python) — TEMPLATE. Copy me into your repo', kind: 'text', template: 'ci-python' },
441
+ { marker: 'Release (tag) — TEMPLATE. Copy me into your repo', kind: 'text', template: 'release-tag' },
442
+ { marker: 'Release (auto) — TEMPLATE. Copy me into your repo', kind: 'text', template: 'release-auto' },
443
+ { marker: 'Deploy (SSH/rsync to shared hosting) — TEMPLATE. Copy me into your repo', kind: 'text', template: 'deploy-xserver' },
444
+ { marker: 'Branch name — TEMPLATE. Copy me into your repo', kind: 'text', template: 'branch-name' },
445
+ // The header convention itself, unattributed: this catches a copy of any template ADDED LATER
446
+ // without anyone remembering to extend this list — provided the new template keeps the house
447
+ // header. A template that omits it is invisible here, which is worth knowing when writing one.
448
+ { marker: '— TEMPLATE. Copy me into your repo', kind: 'text', template: null },
449
+ // Step names we coined, one per template.
450
+ { marker: 'Resolve Node version', kind: 'step', template: 'ci-node' },
451
+ { marker: 'Detect optional scripts', kind: 'step', template: 'ci-node' },
452
+ { marker: 'Resolve toolchain versions', kind: 'step', template: 'ci-laravel' },
453
+ { marker: 'Prepare throwaway env for build-time codegen (wayfinder)', kind: 'step', template: 'ci-laravel' },
454
+ { marker: 'Resolve Python version', kind: 'step', template: 'ci-python' },
455
+ { marker: 'Detect optional tooling', kind: 'step', template: 'ci-python' },
456
+ { marker: 'Build grouped release summary', kind: 'step', template: 'release-tag' },
457
+ { marker: 'Resolve tag and previous tag', kind: 'step', template: 'release-tag' },
458
+ // release-auto (#425): its two decision steps. The publish step's name is deliberately not a
459
+ // marker — "Publish GitHub Release" is release-tag's too, and would attribute a copy to both.
460
+ { marker: 'Cut a candidate (colab release cut --auto)', kind: 'step', template: 'release-auto' },
461
+ { marker: 'Finalize the newest clean candidate (colab release finalize --auto)', kind: 'step', template: 'release-auto' },
462
+ // deploy-xserver. These two were CHOSEN to differ from the step names in the hand-written deploy
463
+ // workflows this template was derived from ("Setup Node", "Smoke test (…)"), which is the same
464
+ // admission test as above read from the other end: those files must keep classifying as
465
+ // `unrelated`, and a marker they happen to contain would reclassify them as copies and invite an
466
+ // overwrite. Verified against all three before being added here.
467
+ { marker: 'Resolve deploy toolchain', kind: 'step', template: 'deploy-xserver' },
468
+ { marker: 'Verify the deployed site answers', kind: 'step', template: 'deploy-xserver' },
469
+ // branch-name (#348): its one step.
470
+ { marker: 'Check branch name (CONVENTIONS §4)', kind: 'step', template: 'branch-name' },
471
+ // Shared by all three ci-* templates: proves derivation, cannot say from which. Note the exact
472
+ // parenthetical — hand-written installers on this fleet say "(pinned binary)", which is why the
473
+ // step NAME discriminates where the URL inside the step does not.
474
+ { marker: 'Install gitleaks (pinned release binary)', kind: 'step', template: null },
475
+ ];
476
+
477
+ function reEscape(s) {
478
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
479
+ }
480
+
481
+ /** Does one fingerprint match? Step markers must appear as an actual `- name:` step, not as prose. */
482
+ function fingerprintHits(text, fp) {
483
+ if (fp.kind === 'text') return text.includes(fp.marker);
484
+ return new RegExp(`^\\s*-\\s*name:\\s*["']?${reEscape(fp.marker)}["']?\\s*$`, 'm').test(text);
485
+ }
486
+
487
+ /**
488
+ * Where did an UNSTAMPED workflow come from? Returns { origin, template, evidence }:
489
+ *
490
+ * derived content evidence says it is a handbook copy. `template` names it when the evidence
491
+ * attributes one, else null (derivation proven, source not).
492
+ * name-only the FILENAME matches a template but the content carries none of it. This is the
493
+ * dangerous case, and it is why a name match is no longer sufficient on its own: the
494
+ * moment `templates/<x>.yml` is added for some `x` that repos already have as their
495
+ * own hand-written workflow, a name-only match would advise `--force` and OVERWRITE
496
+ * a file that never came from us. A shared name is a coincidence, not a lineage.
497
+ * none neither. Somebody's own workflow — say nothing about it, ever.
498
+ */
499
+ function workflowProvenance(text, stem, tmplNames) {
500
+ const hits = text ? WORKFLOW_FINGERPRINTS.filter((fp) => fingerprintHits(text, fp)) : [];
501
+ if (hits.length) {
502
+ const named = [...new Set(hits.map((h) => h.template).filter(Boolean))];
503
+ // One attributed template wins; several (or none) fall back to the filename, and only if that
504
+ // is a real template name. Never guess.
505
+ const template = named.length === 1 ? named[0] : (tmplNames.has(stem) ? stem : null);
506
+ // Cite only the most specific form of each match: the generic header rule always fires
507
+ // alongside the attributed one, and quoting both back at the reader reads like two findings.
508
+ const markers = hits.map((h) => h.marker);
509
+ const evidence = markers.filter((m) => !markers.some((o) => o !== m && o.includes(m)));
510
+ return { origin: 'derived', template, evidence };
511
+ }
512
+ if (tmplNames.has(stem)) return { origin: 'name-only', template: stem, evidence: [] };
513
+ return { origin: 'none', template: null, evidence: [] };
514
+ }
515
+
516
+ /**
517
+ * The single source of the advice both tools print, so the two can never drift apart on the one
518
+ * thing that matters here: whether to suggest asserting provenance.
519
+ * Returns null when there is nothing honest to say.
520
+ */
521
+ function unstampedFinding(prov) {
522
+ if (prov.origin === 'derived') {
523
+ const why = `matched handbook template text (${prov.evidence.map((e) => `"${e}"`).join(', ')})`;
524
+ const how = prov.template
525
+ ? `re-copy deliberately with \`colab template ${prov.template} --force\``
526
+ : 'identify which template it came from before re-copying — the evidence proves it is a copy but not of which template';
527
+ return {
528
+ state: 'unstamped',
529
+ reason: `${why} but carries no stamp — lineage unknown, so replacing it could destroy unknown edits; ${how}`,
530
+ };
531
+ }
532
+ if (prov.origin === 'name-only') {
533
+ return {
534
+ state: 'unrelated',
535
+ reason: `shares a name with templates/${prov.template} but contains none of that template's text — treated as this repo's own file. A matching NAME is not lineage: do NOT \`colab template ${prov.template} --force\`, it would overwrite work that never came from here.`,
536
+ };
537
+ }
538
+ return null;
539
+ }
540
+
541
+ /** Boolean view, kept for callers that only ask "is this ours?". A shared NAME alone is not. */
542
+ function looksLikeHandbookWorkflow(text, stem, tmplNames) {
543
+ return workflowProvenance(text, stem, tmplNames).origin === 'derived';
544
+ }
545
+
546
+ /** A CLAUDE.md that pasted the conventions block (this line is unique to the block template). */
547
+ function looksLikeHandbookClaude(text) {
548
+ return !!text && /follows the \[?colab-handbook/i.test(text);
549
+ }
550
+
551
+ // ---------------------------------------------------------------------------
552
+ // version comparison
553
+ // ---------------------------------------------------------------------------
554
+
555
+ /** Element-wise numeric compare; missing components count as 0. */
556
+ function cmpParts(a, b) {
557
+ const n = Math.max(a.length, b.length);
558
+ for (let i = 0; i < n; i++) {
559
+ const x = a[i] ?? 0;
560
+ const y = b[i] ?? 0;
561
+ if (x !== y) return x < y ? -1 : 1;
562
+ }
563
+ return 0;
564
+ }
565
+
566
+ /** vX.Y.Z comparison. Non-numeric junk sorts as 0 so a malformed stamp never throws. */
567
+ function cmpSemver(a, b) {
568
+ const norm = (s) => String(s).replace(/^v/i, '').split('.').map((n) => parseInt(n, 10) || 0);
569
+ return cmpParts(norm(a), norm(b));
570
+ }
571
+
572
+ // ---------------------------------------------------------------------------
573
+ // classification — the heart of `colab update`
574
+ // ---------------------------------------------------------------------------
575
+
576
+ // Compare tolerantly at the edges only: line endings and trailing blank lines are noise no adopter
577
+ // chose. Anything else counts as a real edit — under-reporting divergence here would let the tool
578
+ // overwrite someone's work, which is the one outcome it must never produce.
579
+ function sameContent(a, b) {
580
+ const norm = (s) => String(s).replace(/\r\n/g, '\n').replace(/\s+$/, '');
581
+ return norm(a) === norm(b);
582
+ }
583
+
584
+ /**
585
+ * Classify one stamped artifact. Returns { state, reason, from, to }.
586
+ *
587
+ * current the stamp is the handbook's version, OR the template genuinely has not changed
588
+ * since that stamp. Nothing to do.
589
+ * behind the stamp is older AND the template changed in between AND the local copy is
590
+ * still pristine as of its own stamp — so it can be regenerated safely.
591
+ * diverged the local copy does not match the template AS OF ITS OWN STAMP: someone edited it.
592
+ * Copy-and-own makes that legitimate (§7), so it is reported and never written.
593
+ * unstamped lineage unknown — handled by the caller, which can see it has no stamp at all.
594
+ * n-a cannot be assessed, with a stated reason (unknown template, a stamp from a version
595
+ * not in this checkout, a stamp newer than the handbook). Never silent.
596
+ *
597
+ * `comparable: false` (the CLAUDE block) means the artifact's pristine form cannot be reconstructed,
598
+ * so divergence is undecidable and the classification stops at current/behind.
599
+ */
600
+ function classifyStamped(opts) {
601
+ const { root, hb, templateName, stampVersion, localText, comparable = true, tmplNames } = opts;
602
+
603
+ if (hb.untagged || !hb.hasGit) {
604
+ return { state: 'n-a', reason: 'handbook is untagged — stamp comparison inactive', from: stampVersion, to: hb.version };
605
+ }
606
+ if (templateName !== null && !tmplNames.has(templateName)) {
607
+ return { state: 'n-a', reason: `names unknown template "${templateName}" — not in the handbook's templates/`, from: stampVersion, to: hb.version };
608
+ }
609
+ if (cmpSemver(stampVersion, hb.version) > 0) {
610
+ return { state: 'n-a', reason: `stamp is NEWER than handbook ${hb.version} — clock skew or a hand-edited stamp`, from: stampVersion, to: hb.version };
611
+ }
612
+
613
+ const files = templateName === null ? [CLAUDE_BLOCK_TEMPLATE] : templateFiles(templateName);
614
+ const { verifiable, changed } = templateChangedSince(root, files, stampVersion);
615
+ if (!verifiable) {
616
+ return { state: 'n-a', reason: `stamped @ ${stampVersion}, a version not in this handbook checkout — fetch tags, or re-copy`, from: stampVersion, to: hb.version };
617
+ }
618
+ if (!changed) {
619
+ const why = cmpSemver(stampVersion, hb.version) === 0
620
+ ? 'stamped at the current handbook version'
621
+ : `template unchanged since ${stampVersion}`;
622
+ return { state: 'current', reason: why, from: stampVersion, to: hb.version };
623
+ }
624
+
625
+ // The template moved. Whether we may refresh depends on whether the copy is still pristine.
626
+ if (!comparable) {
627
+ return { state: 'behind', reason: 'template changed since this stamp', from: stampVersion, to: hb.version };
628
+ }
629
+ const pristine = templateAt(root, stampVersion, templateName);
630
+ if (pristine === null) {
631
+ return { state: 'n-a', reason: `cannot read templates/${templateName} at ${stampVersion} — cannot tell pristine from edited`, from: stampVersion, to: hb.version };
632
+ }
633
+ const expected = stampLine(templateName, stampVersion) + pristine;
634
+ if (sameContent(localText, expected)) {
635
+ return { state: 'behind', reason: 'pristine copy, template changed since this stamp', from: stampVersion, to: hb.version };
636
+ }
637
+ return { state: 'diverged', reason: `hand-edited since it was copied @ ${stampVersion} — copy-and-own, review by hand`, from: stampVersion, to: hb.version };
638
+ }
639
+
640
+ /**
641
+ * Classify the frozen CLI copy: { state, reason, from, to }, with state one of
642
+ * current / behind / n-a.
643
+ *
644
+ * Answered by `git log`, not by comparing version strings — so a handbook release that touched no
645
+ * CLI code does not tell every machine its frozen copy is stale.
646
+ *
647
+ * The upper bound is the latest TAG, not HEAD, and that is the whole difference from a template
648
+ * copy. A stamp records a version, so measuring it to HEAD compares two different units: any
649
+ * unreleased commit under FROZEN_SOURCES marked every machine `behind` until the next tag. That
650
+ * re-coupled precisely what freezing decouples — `behind` was computed against the working tree,
651
+ * and its advertised remedy (`install.sh --tools`) copies FROM the working tree, so on a machine
652
+ * where the handbook is being developed the tool continuously advised services to adopt untagged
653
+ * code. It also misreported worst for maintainers (HEAD ahead of the tag is their resting state)
654
+ * and best for pure consumers, and `colab update`'s exit code rides on it, so anything scripting
655
+ * it flapped red for the whole window between a CLI commit and the next tag.
656
+ *
657
+ * `behind` therefore means: a RELEASED CLI change exists that this machine lacks. True regardless
658
+ * of what the local checkout happens to be doing.
659
+ *
660
+ * No `diverged` state, and that is the one real difference from a template copy. A template is
661
+ * copy-and-own: the adopter is entitled to edit it, so an edit must be detected and protected. The
662
+ * frozen CLI is a CACHE of this repo's own tool — nobody owns it, install.sh overwrites it wholesale
663
+ * on every run, and a hand-edited one is a machine to fix, not an edit to preserve.
664
+ */
665
+ function classifyFrozen(opts) {
666
+ const { root, hb, stampVersion } = opts;
667
+
668
+ if (hb.untagged || !hb.hasGit) {
669
+ return { state: 'n-a', reason: 'handbook is untagged — stamp comparison inactive', from: stampVersion || null, to: hb.version };
670
+ }
671
+ if (!stampVersion) {
672
+ return { state: 'n-a', reason: `no ${FROZEN_STAMP_FILE} beside the frozen copy — lineage unknown, re-run install.sh --tools`, from: null, to: hb.version };
673
+ }
674
+ if (cmpSemver(stampVersion, hb.version) > 0) {
675
+ return { state: 'n-a', reason: `stamp is NEWER than handbook ${hb.version} — this machine froze from a checkout ahead of here`, from: stampVersion, to: hb.version };
676
+ }
677
+
678
+ const { verifiable, changed } = templateChangedSince(root, FROZEN_SOURCES, stampVersion, hb.version);
679
+ if (!verifiable) {
680
+ return { state: 'n-a', reason: `stamped @ ${stampVersion}, a version not in this handbook checkout — fetch tags, or re-freeze`, from: stampVersion, to: hb.version };
681
+ }
682
+ if (!changed) {
683
+ const why = cmpSemver(stampVersion, hb.version) === 0
684
+ ? 'frozen at the current handbook version'
685
+ : `no released CLI change since ${stampVersion}`;
686
+ return { state: 'current', reason: why, from: stampVersion, to: hb.version };
687
+ }
688
+ return { state: 'behind', reason: `${hb.version} changed the CLI since ${stampVersion} — re-run install.sh --tools to re-freeze`, from: stampVersion, to: hb.version };
689
+ }
690
+
691
+ module.exports = {
692
+ CLAUDE_BLOCK_TEMPLATE, WORKFLOW_FINGERPRINTS,
693
+ FROZEN_STAMP_NAME, FROZEN_STAMP_FILE, FROZEN_SOURCES, classifyFrozen,
694
+ AUTHORITY_FLIP_VERSION,
695
+ gitIn, gitCommonDir, isHandbookItself,
696
+ handbookInfo, freezeVersion, templateNames, templateFiles, templateChangedSince, templateAt,
697
+ AXES, axesPredating,
698
+ WRITES_VETO_MARKER, writesRulingKnownAt,
699
+ stampLine, stampCommentPrefix, insertStamp, parseWorkflowStamp, parseClaudeStamp,
700
+ fingerprintHits, workflowProvenance, unstampedFinding,
701
+ looksLikeHandbookWorkflow, looksLikeHandbookClaude,
702
+ cmpParts, cmpSemver, sameContent, classifyStamped,
703
+ };