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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +310 -3
  3. package/README.vi.md +280 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +137 -0
  22. package/templates/release-auto.yml +475 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13790 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +259 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify.js +188 -0
  63. package/tools/lib/npm-publish-guard.js +242 -0
  64. package/tools/lib/orphan-worktree.js +127 -0
  65. package/tools/lib/owner-branch.js +182 -0
  66. package/tools/lib/place.js +782 -0
  67. package/tools/lib/ports.js +167 -0
  68. package/tools/lib/procs.js +185 -0
  69. package/tools/lib/readiness.js +240 -0
  70. package/tools/lib/records.js +185 -0
  71. package/tools/lib/refs-brake.js +95 -0
  72. package/tools/lib/release-channel.js +99 -0
  73. package/tools/lib/release-cut.js +822 -0
  74. package/tools/lib/release-finalize.js +521 -0
  75. package/tools/lib/release-policy.js +358 -0
  76. package/tools/lib/release-tag.js +225 -0
  77. package/tools/lib/ship-batch.js +277 -0
  78. package/tools/lib/ship-roles.js +71 -0
  79. package/tools/lib/ship-target-sync.js +181 -0
  80. package/tools/lib/shipguard.js +317 -0
  81. package/tools/lib/shipped-branch.js +56 -0
  82. package/tools/lib/solo.js +213 -0
  83. package/tools/lib/squash.js +515 -0
  84. package/tools/lib/stale-base.js +70 -0
  85. package/tools/lib/stamp.js +740 -0
  86. package/tools/lib/state.js +262 -0
  87. package/tools/lib/teardown.js +83 -0
  88. package/tools/lib/trust-humans.js +104 -0
  89. package/tools/lib/util.js +98 -0
  90. package/tools/lib/wake.js +188 -0
  91. package/tools/lib/workflow-triggers.js +273 -0
  92. package/tools/lib/writes-authority.js +237 -0
  93. package/tools/lib/yaml.js +101 -0
  94. package/bin/cli.js +0 -3
@@ -0,0 +1,3035 @@
1
+ #!/usr/bin/env node
2
+ // colab-handbook convention audit.
3
+ //
4
+ // This is NOT in-repo CI. It is a CLI you run locally (or on a schedule) that audits
5
+ // MANY repositories across MULTIPLE owners at once — five of them, GitHub orgs and
6
+ // personal accounts alike — plus local-only repos that have no GitHub presence
7
+ // at all. That breadth is the point: the failure mode it exists to catch is drift
8
+ // BETWEEN repos, which no single repo's CI can ever see.
9
+ //
10
+ // Why it left CI: a convention guard living inside each repo can only check the repo
11
+ // it ships in, has to be copied everywhere to be useful, and rots differently in each
12
+ // copy. One external auditor with one source of truth is simpler and honest about
13
+ // what it is — an advisory report, not a gate.
14
+ //
15
+ // Dependencies: none. Plain Node, plus `gh` shelled out for GitHub API reads (only
16
+ // when a repo is given as an owner/name slug rather than a local path).
17
+ //
18
+ // It also runs RECONCILIATION checks: copied handbook artifacts carry a stamp naming
19
+ // the template and the handbook version they were copied at (see `colab template`).
20
+ // This audit compares each stamp against the handbook's own git history and flags a
21
+ // repo whose copy is now behind a changed template — so an adopted repo finds out via
22
+ // the audit, not by luck. The handbook is this checkout (the audit knows its own
23
+ // location); its current version is `git describe --tags --abbrev=0`.
24
+ //
25
+ // Repo list resolution (highest precedence first):
26
+ // 1. --config <path> explicit; errors if missing
27
+ // 2. ~/.colab/repos.txt machine-local fleet registry (PRIVATE, not committed)
28
+ // 3. <this dir>/repos.txt the committed neutral example (fallback only)
29
+ // (COLAB_HOME overrides ~/.colab, matching the colab CLI.)
30
+ //
31
+ // Usage:
32
+ // node audit.mjs # audit everything in the resolved repo list
33
+ // node audit.mjs --local ~/code/foo # audit one local path, ad hoc
34
+ // node audit.mjs --config other.txt # a different repo list
35
+ // node audit.mjs --json # machine-readable
36
+ // node audit.mjs --quiet # only repos with findings
37
+ // node audit.mjs --identity # also scan PUBLIC repository METADATA (description,
38
+ // # topics, homepage, name) against the operator's
39
+ // # private identity vocabulary — see "Identity" below
40
+ //
41
+ // Identity (--identity): metadata never passes through git, so the pre-commit identity scan
42
+ // (templates/pre-commit-identity) structurally cannot see it, and it is the first thing a
43
+ // visitor reads. This is the periodic sweep for it. The vocabulary is supplied by path and
44
+ // kept outside every repo — COLAB_IDENTITY_VOCAB, else ${COLAB_HOME:-~/.colab}/identity-
45
+ // vocabulary — and is never shipped, printed, or written into a report. Off unless asked
46
+ // for: it needs the network, and a fleet sweep must stay runnable offline.
47
+ //
48
+ // Exit code: 0 when every repo passes, 1 when any repo has a finding, 2 on a usage
49
+ // error. Findings never crash the run — a repo missing project.yml is a result, not
50
+ // an exception.
51
+
52
+ import { execFileSync } from "node:child_process";
53
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
54
+ import { join, resolve, basename, dirname } from "node:path";
55
+ import { homedir } from "node:os";
56
+ import { fileURLToPath } from "node:url";
57
+ import { createRequire } from "node:module";
58
+
59
+ // The stamp/drift logic is SHARED with `colab update` (tools/lib/stamp.js), which refreshes what
60
+ // this tool reports. Two readings of a stamp that disagreed about what "behind" means is the
61
+ // two-places-drift disease this handbook exists to kill, so there is one implementation. It is
62
+ // CommonJS because the CLI is; `createRequire` is how ESM consumes it.
63
+ const require = createRequire(import.meta.url);
64
+ const stamp = require("../tools/lib/stamp.js");
65
+ // The convention-label set is shared with adoption/sync (they provision what this reports),
66
+ // so the three surfaces cannot drift about what the full set is. See tools/lib/labels.js.
67
+ const { missingConventionLabels, staleConventionDescriptions, MINIMAL_LABEL_NAMES } = require("../tools/lib/labels.js");
68
+ // #393: "adopted locally, not committed" — one classifier, shared with `colab adopt --local`.
69
+ const { localAdoptionState } = require("../tools/lib/local-adopt.js");
70
+ // #144's authority-flip precedence ladder — shared with `tools/colab` for the same reason
71
+ // every other cross-tool reading in this file is: two implementations of "which key governs"
72
+ // is exactly the two-places-drift disease this handbook exists to kill.
73
+ const axisAuthority = require("../tools/lib/axis-authority.js");
74
+ // #137's falsifier evidence-gathering — shared with `colab adopt` (#199) for the identical
75
+ // reason: `install.sh` freezes tools/colab + tools/lib/ only, nothing under audit/ is frozen,
76
+ // so anything both need has to live in tools/lib/. This module only gathers evidence; the
77
+ // severity policy built on top of it (warn vs fail, the 2-of-5 reach) stays here.
78
+ const {
79
+ VERSION_TAG_RE, versionShapedTags, DEPLOY_BASENAME_RE, consumerEvidence, describeEvidence,
80
+ } = require("../tools/lib/consumer-evidence.js");
81
+ // #207: the exposure mechanism contract's ONE shared representation — this file used to hand-
82
+ // encode the VALIDATOR half (report every violation) separately from `colab adopt`'s CONSTRUCTOR
83
+ // half (does declaring this exposure value stay possible at all?). Same install.sh-freezes-
84
+ // tools/lib/ reasoning as the other requires on this page.
85
+ const { evaluateExposure } = require("../tools/lib/exposure-shape.js");
86
+ // #208's `writes` split precedence ladder — same shared-module reasoning as axisAuthority
87
+ // above, reused for a second axis rather than a bespoke second mechanism.
88
+ const writesAuthority = require("../tools/lib/writes-authority.js");
89
+ // #337's `release:` block — CONVENTIONS §6's release routes (#421) as one derivation table, plus the
90
+ // narrow-never-widen validation of what a repo declares. Shared with `colab release cut` (#338)
91
+ // so the audit and the tool that cuts tags can never read the routes two ways.
92
+ const releasePolicy = require("../tools/lib/release-policy.js");
93
+ // #394: the owner's-branch block — shape and collisions, shared with `colab deliver` and every
94
+ // push-site guard in the CLI, so the audit and the tool can never disagree about what it means.
95
+ const ownerBranchLib = require("../tools/lib/owner-branch.js");
96
+ const npmGuard = require("../tools/lib/npm-publish-guard.js");
97
+ const { parseWorkflowOn, workflowFiresOnTag, prereleaseTagTriggers, workflowsFiringOnBranchPush } = require("../tools/lib/workflow-triggers.js");
98
+ const shipBatch = require("../tools/lib/ship-batch.js");
99
+ // #383: where migrations live — the one rule `colab ship`'s gate and `release cut` read; the audit
100
+ // validates the `migrations:` declaration against it and reports a `*/migrations/` dir it misses.
101
+ const migrationPaths = require("../tools/lib/migration-paths.js");
102
+ // #398: the `migration-grant:` policy key — read through the same module `colab migration-grant` uses.
103
+ const migrationGrant = require("../tools/lib/migration-grant.js");
104
+ // #407: the optional `trust-humans` list — read through the same module every grant reader uses.
105
+ const trustHumansLib = require("../tools/lib/trust-humans.js");
106
+ // #403: the `live-env:` key — read through the same module `colab gate-hermetic` uses.
107
+ const hermeticLib = require("../tools/lib/hermetic.js");
108
+ // #410: the optional `gate:` block — read through the same module the skills name.
109
+ const gateLib = require("../tools/lib/gate.js");
110
+ // #417: CLAUDE.md as a thin shell over AGENTS.md — the @-import resolver and the tool-block table,
111
+ // shared with `colab adopt` so the shell it writes and the shape the audit checks are one shape.
112
+ const instructionFile = require("../tools/lib/instruction-file.js");
113
+ // #228's identity vocabulary — resolution, parsing, matching and REDACTION. Shared with the
114
+ // conformance test that holds it and the shell hook (templates/pre-commit-identity) to the
115
+ // same semantics; the shell scanner cannot require it (a template lands in repos with no
116
+ // Node and no tools/lib/), which is exactly why the semantics needed one written home.
117
+ const identity = require("../tools/lib/identity.js");
118
+ const {
119
+ handbookInfo, templateNames, templateChangedSince, cmpParts, cmpSemver,
120
+ parseWorkflowStamp, parseClaudeStamp, workflowProvenance, unstampedFinding, looksLikeHandbookClaude,
121
+ } = stamp;
122
+
123
+ const HERE = dirname(fileURLToPath(import.meta.url));
124
+ // audit/ lives inside the handbook checkout; COLAB_HANDBOOK overrides for running the
125
+ // audit from elsewhere (or for tests that point at a scratch handbook).
126
+ const HANDBOOK_ROOT = process.env.COLAB_HANDBOOK ? resolve(process.env.COLAB_HANDBOOK) : resolve(HERE, "..");
127
+ const COLAB_HOME = process.env.COLAB_HOME || join(homedir(), ".colab");
128
+
129
+ // ---------------------------------------------------------------------------- args
130
+
131
+ function parseArgs(argv) {
132
+ // config === null means "resolve from the precedence chain"; a string means explicit.
133
+ const opts = { config: null, locals: [], slugs: [], json: false, quiet: false, help: false, identity: false };
134
+ for (let i = 0; i < argv.length; i++) {
135
+ const a = argv[i];
136
+ if (a === "--json") opts.json = true;
137
+ else if (a === "--quiet" || a === "-q") opts.quiet = true;
138
+ else if (a === "--identity") opts.identity = true;
139
+ else if (a === "--local") {
140
+ const p = argv[++i];
141
+ if (!p) die("--local needs a path");
142
+ opts.locals.push(p);
143
+ } else if (a === "--config" || a === "-c") {
144
+ const p = argv[++i];
145
+ if (!p) die("--config needs a path");
146
+ opts.config = p;
147
+ } else if (a === "--help" || a === "-h") {
148
+ // Signal, don't print-and-exit. The help text is ~12 KB — larger than a
149
+ // pipe buffer — so exiting here truncated it for any reader that is not
150
+ // a terminal. See the note above process.exitCode in main.
151
+ opts.help = true;
152
+ return opts;
153
+ } else if (a.startsWith("-")) die(`unknown flag: ${a}`);
154
+ else opts.slugs.push(a); // bare argument = slug or path
155
+ }
156
+ return opts;
157
+ }
158
+
159
+ // Resolve the repo-list file per the documented precedence. Returns { path, source }
160
+ // or null when auditing only --local / positional targets (no list needed).
161
+ function resolveConfig(opts) {
162
+ if (opts.config) {
163
+ if (!existsSync(opts.config)) die(`config not found: ${opts.config}`);
164
+ return { path: opts.config, source: "--config" };
165
+ }
166
+ const local = join(COLAB_HOME, "repos.txt");
167
+ if (existsSync(local)) return { path: local, source: COLAB_HOME + "/repos.txt" };
168
+ const bundled = join(HERE, "repos.txt");
169
+ return { path: bundled, source: "bundled example (audit/repos.txt)" };
170
+ }
171
+
172
+ function die(msg) {
173
+ // Deliberately keeps process.exit(): die() is a control-flow terminator called
174
+ // from mid-loop and mid-function, where returning would let the caller carry
175
+ // on with invalid state. Exiting is safe here because it writes a single short
176
+ // line to stderr — always well under a pipe buffer, and stderr is a separate
177
+ // buffer from the JSON on stdout, so it cannot be the thing that gets cut.
178
+ console.error(`audit: ${msg}`);
179
+ process.exit(2);
180
+ }
181
+
182
+ // ------------------------------------------------------------------- tiny YAML read
183
+ //
184
+ // project.yml is a flat mapping of scalars by design. A hand-rolled reader keeps this
185
+ // tool dependency-free; anything it cannot understand is reported as a parse finding
186
+ // rather than silently ignored, so the narrowness is visible instead of dangerous.
187
+ //
188
+ // ONE indented form is accepted: a block sequence of scalars under a key, because
189
+ // `integration:` is a list and a descriptor that cannot express a list would push repos
190
+ // into encoding one in a string. Nesting of every other shape remains a finding — the
191
+ // reader stays narrow on purpose, and the narrowness stays visible.
192
+ //
193
+ // ONE nested map is accepted too, and only under a key named in NESTED_MAP_KEYS: a single
194
+ // level of `sub: scalar` pairs (#337's `release:` block, #394's `owner:`, #410's `gate:`). The allow-list is the check — a
195
+ // nested map under any other key, a second level, or a list item under a map key is still
196
+ // a finding, so this is one named exception, not a general loosening.
197
+ //
198
+ // (The `colab` CLI reads the same file through tools/lib/yaml.js, which accepts nested
199
+ // maps as well. The two are deliberately NOT merged: this one's refusal to parse nesting
200
+ // is a CHECK — it is how an over-clever descriptor gets reported instead of silently
201
+ // half-read — while the CLI only needs to consume valid files. Sharing one reader would
202
+ // mean deleting the check.)
203
+
204
+ function parseScalarValue(raw) {
205
+ let val = raw.replace(/\s+#.*$/, "").trim(); // strip trailing comment
206
+ if (/^".*"$/.test(val) || /^'.*'$/.test(val)) return val.slice(1, -1);
207
+ if (val === "" || val === "null" || val === "~") return null;
208
+ if (val === "true") return true;
209
+ if (val === "false") return false;
210
+ return val;
211
+ }
212
+
213
+ const NESTED_MAP_KEYS = new Set(["release", "owner", "gate"]); // owner: #394 · gate: #410
214
+
215
+ function parseFlatYaml(text) {
216
+ const out = {};
217
+ const problems = [];
218
+ // The key whose block sequence may follow. Cleared by any column-0 line, so a `- item`
219
+ // can never attach to a key it does not sit directly under.
220
+ let listKey = null;
221
+ // The NESTED_MAP_KEYS key whose one-level map may follow, and the indent its first pair
222
+ // set — a pair at any other indent is a second level (or a stray), and is reported.
223
+ let mapKey = null;
224
+ let mapIndent = null;
225
+ text.split(/\r?\n/).forEach((raw, idx) => {
226
+ const line = raw.replace(/\t/g, " ");
227
+ if (!line.trim() || /^\s*#/.test(line)) return;
228
+ if (/^\s+/.test(line)) {
229
+ const item = line.match(/^\s+-\s*(.*)$/);
230
+ if (listKey !== null && item) {
231
+ if (!Array.isArray(out[listKey])) out[listKey] = [];
232
+ out[listKey].push(parseScalarValue(item[1]));
233
+ return;
234
+ }
235
+ const pair = line.match(/^(\s+)([A-Za-z0-9_.-]+)\s*:\s*(.*)$/);
236
+ if (mapKey !== null && pair && !item) {
237
+ const [, indent, sub, subRaw] = pair;
238
+ if (mapIndent === null) mapIndent = indent.length;
239
+ const subTrimmed = subRaw.replace(/\s+#.*$/, "").trim();
240
+ if (indent.length === mapIndent && subTrimmed !== "" && !/^\[.*\]$/.test(subTrimmed)) {
241
+ if (out[mapKey] === null || typeof out[mapKey] !== "object") out[mapKey] = {};
242
+ // #439: an unquoted whole number under `release:` is a number, as the CLI's YAML reader
243
+ // reads it (`candidates-per-day: 1`, `final-grant: 7`) — kept a string, the one reading
244
+ // in release-policy.js failed a valid declaration that colab release cut accepts. A
245
+ // quoted "1" stays a string on both readers, and fails on both.
246
+ const scalar = parseScalarValue(subRaw);
247
+ out[mapKey][sub] = mapKey === "release" && typeof scalar === "string" && /^[0-9]+$/.test(subTrimmed) ? Number(scalar) : scalar;
248
+ return;
249
+ }
250
+ problems.push(`line ${idx + 1}: "${mapKey}:" takes one level of "key: scalar" pairs — nothing deeper, and no lists`);
251
+ return;
252
+ }
253
+ problems.push(`line ${idx + 1}: nested/indented YAML is not supported by this reader (flat key: value, or a "- item" list under a key)`);
254
+ return;
255
+ }
256
+ listKey = null;
257
+ mapKey = null;
258
+ mapIndent = null;
259
+ const m = line.match(/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/);
260
+ if (!m) {
261
+ problems.push(`line ${idx + 1}: not a "key: value" pair -> ${line.trim()}`);
262
+ return;
263
+ }
264
+ const [, key, rawVal] = m;
265
+ const trimmed = rawVal.replace(/\s+#.*$/, "").trim();
266
+ if (/^\[.*\]$/.test(trimmed)) {
267
+ const inner = trimmed.slice(1, -1).trim();
268
+ out[key] = inner === "" ? [] : inner.split(",").map((s) => parseScalarValue(s));
269
+ return;
270
+ }
271
+ out[key] = parseScalarValue(rawVal);
272
+ // A key with a genuinely empty value may open a block sequence on the next lines. It
273
+ // stays `null` if none follows — `production:` must keep meaning null, not [].
274
+ // A NESTED_MAP_KEYS key opens a one-level map instead (and never a list).
275
+ if (trimmed === "") {
276
+ if (NESTED_MAP_KEYS.has(key)) mapKey = key;
277
+ else listKey = key;
278
+ }
279
+ });
280
+ return { data: out, problems };
281
+ }
282
+
283
+ // ------------------------------------------------------------------ version helpers
284
+
285
+ // "^8.3" ">=22.1 <23" "v22" "22.x" -> "8.3" "22.1" "22" "22"
286
+ function normaliseVersion(raw) {
287
+ if (raw === null || raw === undefined) return null;
288
+ const s = String(raw).trim();
289
+ const m = s.match(/(\d+(?:\.\d+)*)/);
290
+ return m ? m[1] : null;
291
+ }
292
+
293
+ function major(v) {
294
+ const n = normaliseVersion(v);
295
+ return n ? n.split(".")[0] : null;
296
+ }
297
+
298
+ function isRange(s) {
299
+ const t = String(s).trim();
300
+ return /^[\^~><=]/.test(t) || /[\s|]/.test(t) || /\.(\*|x)$/i.test(t);
301
+ }
302
+
303
+ // (cmpParts comes from tools/lib/stamp.js — one numeric version compare, shared.)
304
+
305
+ // Agreement at the precision both sides actually state. "22" vs "22.1" agree —
306
+ // nobody declared the minor, so nobody is claiming anything about it. "8.3" vs "8.4"
307
+ // DISagree, because both sides stated a minor and they differ. This matters: a Node
308
+ // major is the unit that breaks builds, while PHP minors are real feature releases.
309
+ function prefixAgree(a, b) {
310
+ const A = (normaliseVersion(a) || "").split(".").map(Number);
311
+ const B = (normaliseVersion(b) || "").split(".").map(Number);
312
+ if (!A.length || !B.length) return true;
313
+ const n = Math.min(A.length, B.length);
314
+ for (let i = 0; i < n; i++) if (A[i] !== B[i]) return false;
315
+ return true;
316
+ }
317
+
318
+ // Does a concrete version satisfy a manifest constraint like "^8.3", "~22.1",
319
+ // ">=22 <23"? Whitespace-separated clauses are ANDed, which is how both npm and
320
+ // composer read them. Anything unparseable returns true — this tool reports drift,
321
+ // it does not invent violations out of syntax it does not understand.
322
+ function satisfiesConstraint(version, constraint) {
323
+ const v = normaliseVersion(version);
324
+ if (!v) return true;
325
+ const vp = v.split(".").map(Number);
326
+ const clauses = String(constraint).trim().split(/\s+/).filter(Boolean);
327
+ if (!clauses.length) return true;
328
+ return clauses.every((cl) => {
329
+ const m = cl.match(/^(\^|~|>=|<=|>|<|=)?v?(\d+(?:\.\d+)*)/);
330
+ if (!m) return true;
331
+ const op = m[1] || "=";
332
+ const t = m[2].split(".").map(Number);
333
+ const c = cmpParts(vp, t);
334
+ switch (op) {
335
+ case "^": // same major, at or above
336
+ return vp[0] === t[0] && c >= 0;
337
+ case "~": // same major.minor (when a minor was given), at or above
338
+ return vp[0] === t[0] && (t.length < 2 || vp[1] === t[1]) && c >= 0;
339
+ case ">=": return c >= 0;
340
+ case ">": return c > 0;
341
+ case "<=": return c <= 0;
342
+ case "<": return c < 0;
343
+ default: return prefixAgree(v, m[2]);
344
+ }
345
+ });
346
+ }
347
+
348
+
349
+ // ------------------------------------------------------- handbook version + stamps
350
+ //
351
+ // Reconciliation rests on two facts the audit can establish locally:
352
+ // 1. The handbook's CURRENT version — `git describe --tags --abbrev=0` in this
353
+ // checkout. Before any tag exists that command fails; we then treat the version
354
+ // as `v0` and mark the handbook "untagged", which DEACTIVATES stamp comparisons
355
+ // (there is no real version line to compare against) rather than failing.
356
+ // 2. Whether a template CHANGED since a given stamp — `git log <stamp>..HEAD` scoped
357
+ // to that template's file. Non-empty history = the adopter's copy is behind.
358
+
359
+ // All of the above now lives in tools/lib/stamp.js, imported at the top of this file:
360
+ // gitIn, handbookInfo, templateNames, cmpSemver, templateChangedSince, parseWorkflowStamp,
361
+ // parseClaudeStamp, WORKFLOW_FINGERPRINTS, workflowProvenance, unstampedFinding, looksLikeHandbookClaude.
362
+ // They take the handbook root explicitly (this file passes HANDBOOK_ROOT) because `colab update`
363
+ // locates the handbook differently.
364
+
365
+ // Run all stamp/reconciliation checks for one repo, pushing findings via fail/warn.
366
+ // Silent when there is nothing to say (the common, healthy case).
367
+ function checkStamps(src, hb, tmplNames, fail, warn, { ceremony = "standard", missingAxes = [], predatesAxes = [], writesRaw = null } = {}) {
368
+ const cur = hb.version;
369
+
370
+ const compareStamp = (kind, name, stampVersion, files, { isCi = false } = {}) => {
371
+ // Deactivated while the handbook is untagged — a global note already says so.
372
+ if (hb.untagged || !hb.hasGit) return;
373
+ if (name !== null && !tmplNames.has(name)) {
374
+ warn(`${kind} stamped @ ${stampVersion} names unknown template "${name}" — not in handbook templates/`);
375
+ return;
376
+ }
377
+ if (cmpSemver(stampVersion, cur) > 0) {
378
+ warn(`${kind} stamped @ ${stampVersion} is NEWER than handbook current ${cur} — clock skew or a hand-edited stamp`);
379
+ return;
380
+ }
381
+ const { verifiable, changed, ruleNeutral } = templateChangedSince(HANDBOOK_ROOT, files, stampVersion);
382
+ if (!verifiable) {
383
+ warn(`${kind} stamped @ ${stampVersion}, a version not in this handbook checkout — cannot verify drift (fetch tags, or re-copy)`);
384
+ return;
385
+ }
386
+ if (changed) {
387
+ // ceremony: light (#79) downgrades drift on a NON-CI template to an advisory — CI/secret-scan
388
+ // integrity is never optional, on any ceremony value or any production status, so a `ci-*`
389
+ // template copy stays a hard finding regardless (isCi guards this unconditionally, below).
390
+ // This is the "stamp drift on non-CI templates" item project.schema.md's ceremony section
391
+ // names; it exists to stop beta noise from drowning real findings on a repo nobody in the
392
+ // room will comb through, never to let a live repo's CI drift unnoticed — narration (which
393
+ // `light` relaxes) and CI integrity (which it never does) are exactly the two things #175
394
+ // split apart.
395
+ const msg = `${kind} copied @ ${stampVersion} — template changed since (${cur}): review, re-copy via colab template`;
396
+ // ruleNeutral (#272, ruling option C): every commit since the stamp declared itself
397
+ // rule-neutral, by the person who wrote it, at commit time — never inferred here from
398
+ // the diff. Same downgrade shape as ceremony: light and the same CI carve-out: a `ci-*`
399
+ // template stays a hard fail regardless of the declaration, for the identical reason
400
+ // `isCi` already overrides ceremony above. Declaring nothing (the default) is unaffected
401
+ // — that repo gets exactly today's fail.
402
+ if (ruleNeutral && !isCi) warn(`${msg} (declared rule-neutral at commit time — see CONVENTIONS.md §8)`);
403
+ else if (ceremony === "light" && !isCi) warn(`${msg} (ceremony: light — advisory, not a build/secret-scan template)`);
404
+ else fail(msg);
405
+ }
406
+ };
407
+
408
+ // --- workflow copies ---
409
+ for (const wf of src.listDir(".github/workflows").filter((f) => /\.ya?ml$/.test(f))) {
410
+ const text = src.readFile(`.github/workflows/${wf}`);
411
+ const stem = wf.replace(/\.ya?ml$/, "");
412
+ const stamp = parseWorkflowStamp(text);
413
+ if (stamp) {
414
+ const isCi = /^ci-/.test(stamp.name);
415
+ compareStamp(`${wf}`, stamp.name, stamp.version, [`templates/${stamp.name}.yml`, `templates/${stamp.name}.yaml`], { isCi });
416
+ } else {
417
+ // Content decides, never the filename — a workflow that merely SHARES a template's name
418
+ // was not copied from it, and saying otherwise pushes people toward asserting a lineage
419
+ // they never had (the advice being `--force`, that is a data-loss bug once a template of
420
+ // that name exists). `unstampedFinding` is shared with `colab update` so the two tools
421
+ // cannot drift on this. The `unrelated` finding is deliberately NOT raised here: it has no
422
+ // action, and the audit reports drift, not reassurance.
423
+ const finding = unstampedFinding(workflowProvenance(text, stem, tmplNames));
424
+ if (finding && finding.state === 'unstamped') warn(`${wf} unstamped — ${finding.reason}`);
425
+ }
426
+ }
427
+
428
+ // --- CLAUDE.md conventions block ---
429
+ const claude = src.readFile("CLAUDE.md");
430
+ if (claude) {
431
+ const stampInfo = parseClaudeStamp(claude);
432
+ if (stampInfo) {
433
+ compareStamp("CLAUDE block", null, stampInfo.version, ["templates/repo-CLAUDE-block.md"]);
434
+ // Adoption compatibility window (#138): an axis missing on this repo is only a
435
+ // finding when its marker actually PREDATES the axis — never merely undeclared,
436
+ // which stays silent everywhere else (#131/#132/#133/#151's own asymmetry). `warn`
437
+ // only, never `fail`: the marker was not lying when it was written; the question
438
+ // simply did not exist yet.
439
+ if (!hb.untagged && hb.hasGit && missingAxes.length) {
440
+ const { verifiable, axes } = stamp.axesPredating(HANDBOOK_ROOT, stampInfo.version);
441
+ if (verifiable) {
442
+ const predates = missingAxes.filter((a) => axes.includes(a));
443
+ if (predates.length) {
444
+ predates.forEach((a) => predatesAxes.push(a));
445
+ warn(`marker predates the axis model — ${predates.join("/")} entered the model after this repo's stamp @ ${stampInfo.version}; answer ${predates.length > 1 ? "them" : "it"} via CONVENTIONS.md §9's question set (a sync), same as first-time adoption asks (omission stays legal: undeclared, never a default)`);
446
+ }
447
+ }
448
+ }
449
+ // ⚖ #233 sync announcement (#239): a repo whose marker predates the ruling never got
450
+ // told what silence (or its own declared value) now means — the ONLY channel that
451
+ // reaches a repo declaring nothing, because there is no diff to show it (#239's own
452
+ // argument: a change to what silence means cannot be delivered as a diff). Gated on the
453
+ // ruling's own arrival at this repo's stamped ref, not a version number — see
454
+ // `writesRulingKnownAt`'s docstring (tools/lib/stamp.js) for why this deliberately does
455
+ // NOT mirror the `AUTHORITY_FLIP_VERSION`-gated check further down this file, which
456
+ // defers on purpose; this one must not defer at all.
457
+ if (!hb.untagged && hb.hasGit) {
458
+ const { verifiable, known } = stamp.writesRulingKnownAt(HANDBOOK_ROOT, stampInfo.version);
459
+ if (verifiable && !known) warn(writesAuthority.writesSyncAdvisory(writesRaw));
460
+ }
461
+ } else if (looksLikeHandbookClaude(claude)) {
462
+ warn("CLAUDE.md has the conventions block but no colab-handbook stamp — cannot track handbook drift; re-paste the current block");
463
+ }
464
+ }
465
+ }
466
+
467
+ // -------------------------------------------------------- workflow `on:` triggers
468
+ //
469
+ // parseWorkflowOn / githubFilterMatches / workflowFiresOnTag live in tools/lib/workflow-triggers.js
470
+ // (#338) — shared with `colab release cut`, imported near the top of this file.
471
+
472
+ // Minimal shell-glob for branch patterns like `release/*`. Plain names compare as
473
+ // equality; only `*` and `?` are honoured — enough for GitHub branch filters.
474
+ function globMatch(pattern, name) {
475
+ if (!/[*?[]/.test(pattern)) return pattern === name;
476
+ const rx = "^" + pattern.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
477
+ try { return new RegExp(rx).test(name); } catch { return false; }
478
+ }
479
+
480
+ // ------------------------------------------------------------------- repo acquisition
481
+
482
+ function runGh(args) {
483
+ return execFileSync("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
484
+ }
485
+
486
+ // A slug is fetched read-only through the API — nothing is cloned, nothing is written
487
+ // into anyone's working tree.
488
+ function readRemoteFile(slug, path) {
489
+ try {
490
+ return runGh(["api", `repos/${slug}/contents/${path}`, "-H", "Accept: application/vnd.github.raw"]);
491
+ } catch {
492
+ return null;
493
+ }
494
+ }
495
+
496
+ function listRemoteDir(slug, path) {
497
+ try {
498
+ const out = runGh(["api", `repos/${slug}/contents/${path}`, "--jq", ".[].name"]);
499
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
500
+ } catch {
501
+ return [];
502
+ }
503
+ }
504
+
505
+ function listRemoteBranches(slug) {
506
+ try {
507
+ const out = runGh(["api", `repos/${slug}/branches`, "--paginate", "--jq", ".[].name"]);
508
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
509
+ } catch {
510
+ return null; // null = could not determine, distinct from "no branches"
511
+ }
512
+ }
513
+
514
+ // Same null/[] contract as listRemoteBranches: null = could not determine (no remote, no
515
+ // auth, gh absent, API error), never invented as "no tags". Used by the exposure/channels
516
+ // falsifiers (#137) — a version-shaped tag is evidence against a declared "nothing consumes
517
+ // this" claim, whether the source is local or remote.
518
+ function listRemoteTags(slug) {
519
+ try {
520
+ const out = runGh(["api", `repos/${slug}/tags`, "--paginate", "--jq", ".[].name"]);
521
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
522
+ } catch {
523
+ return null;
524
+ }
525
+ }
526
+
527
+ // Labels live on GitHub, not in the working tree, so this is the audit's one check that
528
+ // needs the tracker. `null` means "could not determine" — no remote, no auth, gh absent,
529
+ // API error — and the caller stays SILENT on it rather than warning: unlike branches
530
+ // (every git repo has them), labels are a GitHub-only concept and a remote-less or
531
+ // offline audit legitimately cannot see them. A warn per offline repo would be noise,
532
+ // and we cannot assert a label is missing when we could not read the set at all.
533
+ // Each entry is { name, description } (#364) — one JSON object per line from `--jq`, so a
534
+ // paginated read never has to splice arrays. A line that does not parse makes the whole read
535
+ // null: a half-read set would report the unread half as "missing".
536
+ function listRemoteLabels(slug) {
537
+ try {
538
+ const out = runGh(["api", `repos/${slug}/labels`, "--paginate", "--jq", ".[] | {name, description}"]);
539
+ return out.split("\n").map((s) => s.trim()).filter(Boolean).map((line) => {
540
+ const l = JSON.parse(line);
541
+ return { name: String(l.name), description: typeof l.description === "string" ? l.description : "" };
542
+ });
543
+ } catch {
544
+ return null;
545
+ }
546
+ }
547
+
548
+ // The repository's own METADATA — name, description, homepage, topics, visibility — which
549
+ // lives only on GitHub and never passes through git. #228's whole reason for existing as a
550
+ // second mechanism: no commit-time hook can see any of it.
551
+ //
552
+ // Three outcomes, never conflated:
553
+ // { status: "ok", data } the API answered
554
+ // { status: "unreadable" } gh is absent, unauthenticated, offline, or the repo is gone —
555
+ // a check that did not run, which the caller reports as a FAIL.
556
+ // It is deliberately NOT the silent null that listRemoteLabels()
557
+ // returns: labels are a provisioning nag, and being unable to read
558
+ // them costs nothing; being unable to read metadata while the
559
+ // operator explicitly asked for an identity scan is a scan that
560
+ // silently did not happen.
561
+ // { status: "no-remote" } (local sources only) nothing on GitHub to have metadata.
562
+ // { status: "remote-unresolved", reason } (local sources only, #376) the checkout's remotes
563
+ // are ambiguous or its `colab.remote` override is broken — the caller
564
+ // fails with `reason`, which names the fix. Never guessed.
565
+ // One issue's state, labels and comments (#441 — a release.final-grant's decision issue), or null
566
+ // when it could not be read. null is never "no decision": the caller fails closed on it.
567
+ function readRemoteIssue(slug, num) {
568
+ try {
569
+ return JSON.parse(runGh(["issue", "view", String(num), "--repo", slug, "--json", "state,labels,comments"]));
570
+ } catch {
571
+ return null;
572
+ }
573
+ }
574
+
575
+ function readRemoteMetadata(slug) {
576
+ try {
577
+ const out = runGh(["api", `repos/${slug}`]);
578
+ return { status: "ok", data: JSON.parse(out) };
579
+ } catch {
580
+ return { status: "unreadable" };
581
+ }
582
+ }
583
+
584
+ // github.com/owner/name, git@github.com:owner/name.git → "owner/name". Non-GitHub or
585
+ // unparseable remotes return null, so a local-only repo (or a self-hosted git remote)
586
+ // contributes no label finding — matching the skill's "no remote" branch.
587
+ function githubSlugFromRemote(url) {
588
+ if (!url) return null;
589
+ const m = String(url).trim().match(/github\.com[:/]+([^/]+)\/(.+?)(?:\.git)?\/?$/);
590
+ return m ? `${m[1]}/${m[2]}` : null;
591
+ }
592
+
593
+ // Which git remote a LOCAL checkout's GitHub URL is read from (#376) — the same resolver every
594
+ // `colab` command uses since #301 (tools/lib/git.js `remoteInfo`; rule order in tools/README.md,
595
+ // "Which remote"), so the audit and the CLI can never pick two different remotes in one clone. A
596
+ // repo with an `origin` resolves to it, so it reads exactly the URL it read before this existed.
597
+ // Ambiguous remotes (several, none `origin`, no override) resolve to NO url and are REPORTED by
598
+ // the checks below through `remoteProblem()` — never guessed. Imported here rather than in the
599
+ // block above: it serves makeSource alone.
600
+ const gitRemote = require("../tools/lib/git.js");
601
+
602
+ // A uniform accessor so every check below is written once and works for both a local
603
+ // path and a remote slug.
604
+ /** #393: the git facts `localAdoptionState` classifies — tracked / ignored are null outside a
605
+ * git checkout (nothing to say), never guessed. */
606
+ function gitDescriptorFacts(root, exists) {
607
+ const run = (args) => {
608
+ try { execFileSync("git", ["-C", root, ...args], { stdio: ["ignore", "ignore", "ignore"] }); return true; }
609
+ catch (e) { return e && typeof e.status === "number" ? false : null; }
610
+ };
611
+ const inGit = run(["rev-parse", "--git-dir"]);
612
+ if (!inGit) return { exists, tracked: null, ignored: null };
613
+ return {
614
+ exists,
615
+ tracked: run(["ls-files", "--error-unmatch", "--", ".github/project.yml"]),
616
+ ignored: run(["check-ignore", "-q", "--", ".github/project.yml"]),
617
+ };
618
+ }
619
+
620
+ function makeSource(target) {
621
+ if (target.kind === "local") {
622
+ const root = resolve(target.path);
623
+ return {
624
+ label: target.label,
625
+ kind: "local",
626
+ exists: existsSync(root),
627
+ readFile: (p) => {
628
+ const f = join(root, p);
629
+ return existsSync(f) ? readFileSync(f, "utf8") : null;
630
+ },
631
+ listDir: (p) => {
632
+ const d = join(root, p);
633
+ try {
634
+ return existsSync(d) ? readdirSync(d) : [];
635
+ } catch {
636
+ return [];
637
+ }
638
+ },
639
+ branches: () => {
640
+ try {
641
+ const out = execFileSync("git", ["-C", root, "for-each-ref", "--format=%(refname:short)", "refs/heads"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
642
+ const heads = out.split("\n").map((s) => s.trim()).filter(Boolean);
643
+ // Zero local branch refs plus a detached HEAD is what a shallow `pull_request`
644
+ // checkout looks like (actions/checkout defaults to fetch-depth 1 and checks out
645
+ // the merge commit detached, with no refs/heads at all) — not the same claim as
646
+ // "this repo genuinely has no branches". Report it the same way as "not a git
647
+ // checkout": unverifiable, not a trunk-missing finding (#104). This guard is
648
+ // keyed off `refs/heads` alone, on purpose — a real shallow CI checkout has no
649
+ // remote-tracking refs either, so unioning in refs/remotes below never changes
650
+ // whether this fires.
651
+ if (heads.length === 0) {
652
+ try {
653
+ const head = execFileSync("git", ["-C", root, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
654
+ if (head === "HEAD") return null;
655
+ } catch {
656
+ // rev-parse itself failed — fall through and report the (empty) list as-is.
657
+ }
658
+ }
659
+ // A branch that exists only as a remote-tracking ref (refs/remotes/<remote>/<name>)
660
+ // is still a branch in every sense the checks below care about: `git clone
661
+ // --branch main` leaves every OTHER branch — including trunk, on a Tier A/C repo
662
+ // where trunk isn't the default — in exactly this shape, and `colab worktree new`
663
+ // already cuts from origin/<trunk>, never a local ref. Reading refs/heads alone
664
+ // reported that trunk as missing on the most pristine checkout there is (#204).
665
+ // Union it in, stripping the leading "<remote>/" generically (not hard-coded to
666
+ // "origin" — whatever remote is configured) and excluding the symbolic ref every
667
+ // remote carries pointing at its default branch. `refname:short` renders that one
668
+ // two different ways depending on git version: "<remote>/HEAD" (has a slash, would
669
+ // strip to the literal branch name "HEAD") or just "<remote>" with no slash at all
670
+ // (git's shorthand for "this remote's HEAD") — the no-slash form is why entries
671
+ // without a "/" are dropped BEFORE stripping, not after; naively slicing one at
672
+ // `indexOf("/") + 1` over "-1" would keep the whole remote name as a fake branch.
673
+ let remotes = [];
674
+ try {
675
+ const remoteOut = execFileSync("git", ["-C", root, "for-each-ref", "--format=%(refname:short)", "refs/remotes"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
676
+ remotes = remoteOut.split("\n").map((s) => s.trim()).filter(Boolean)
677
+ .filter((s) => s.includes("/"))
678
+ .map((s) => s.slice(s.indexOf("/") + 1))
679
+ .filter((s) => s && s !== "HEAD");
680
+ } catch {
681
+ // no remotes configured, or the command failed — local refs alone still stand.
682
+ }
683
+ return [...new Set([...heads, ...remotes])];
684
+ } catch {
685
+ return null; // not a git repo, or git unavailable
686
+ }
687
+ },
688
+ // refs/heads only, no remote union — used exactly once, by the "checkout parked on
689
+ // the wrong branch" finding below, to tell "trunk exists but this checkout drifted
690
+ // off it" (fire) apart from "trunk has never had a local ref here" (a fresh `git
691
+ // clone --branch <default>` or a CI checkout — nothing to "return" the checkout to,
692
+ // because it was never there). branches() above stays the general-purpose,
693
+ // remote-inclusive answer for existence checks; this one exists to preserve the
694
+ // local/remote distinction that decision specifically needs (#204).
695
+ localBranches: () => {
696
+ try {
697
+ const out = execFileSync("git", ["-C", root, "for-each-ref", "--format=%(refname:short)", "refs/heads"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
698
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
699
+ } catch {
700
+ return null;
701
+ }
702
+ },
703
+ currentBranch: () => {
704
+ try {
705
+ return execFileSync("git", ["-C", root, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
706
+ } catch {
707
+ return null;
708
+ }
709
+ },
710
+ // Every tag name, no filtering — the exposure/channels falsifiers (#137) decide
711
+ // which are version-shaped. null = could not determine (not a git repo, git
712
+ // unavailable), same contract as branches() above.
713
+ tags: () => {
714
+ try {
715
+ const out = execFileSync("git", ["-C", root, "tag", "--list"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
716
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
717
+ } catch {
718
+ return null;
719
+ }
720
+ },
721
+ // Commits whose diff to .github/project.yml touched a line matching `^\s*<key>:`,
722
+ // newest first — the raw material declaredStateAge() (#137) walks to find when a
723
+ // declared axis last changed. `-G`, not `-S`: `-S` counts occurrence-count changes
724
+ // (a line moved elsewhere with the same net count would be invisible to it); `-G`
725
+ // matches any diff touching a line the pattern matches, which is what "did this
726
+ // key's line change" actually means. Capped at 50 commits — a repo whose descriptor
727
+ // has changed that many times has no honest "since when" answer either way, and the
728
+ // cap becomes one of declaredStateAge's own lower-bound degradations rather than an
729
+ // unbounded git log over a huge history. null = could not determine (not a git repo,
730
+ // git unavailable); the caller stays silent on null, same contract as tags()/
731
+ // branches() above.
732
+ descriptorHistory: (key) => {
733
+ try {
734
+ const out = execFileSync(
735
+ "git",
736
+ ["-C", root, "log", `-G^\\s*${key}:`, "--max-count=50", "--format=%H %ct", "--", ".github/project.yml"],
737
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
738
+ );
739
+ const lines = out.split("\n").map((s) => s.trim()).filter(Boolean);
740
+ if (!lines.length) return null;
741
+ return lines.map((l) => {
742
+ const sp = l.indexOf(" ");
743
+ return { sha: l.slice(0, sp), epoch: Number(l.slice(sp + 1)) };
744
+ });
745
+ } catch {
746
+ return null;
747
+ }
748
+ },
749
+ // A file's content AT a given ref (`git show <ref>:<path>`), or null — the same
750
+ // shape as tools/lib/stamp.js's templateAt, reused here rather than duplicated
751
+ // because both answer "what did this path look like as of some historical point."
752
+ // null covers every unreadable case identically: the ref does not resolve (a
753
+ // shallow clone's history boundary, e.g. `<sha>^` past the fetched depth), the path
754
+ // did not exist at that ref, or git itself is unavailable — declaredStateAge (#137)
755
+ // reads null as "cannot see further back" and degrades to a lower bound rather than
756
+ // guessing.
757
+ fileAt: (ref, path) => {
758
+ try {
759
+ return execFileSync("git", ["-C", root, "show", `${ref}:${path}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
760
+ } catch {
761
+ return null;
762
+ }
763
+ },
764
+ // A LINKED worktree is on a feature branch by design — that is the whole point of
765
+ // one. Only the main checkout owes the on-trunk invariant, so the caller skips the
766
+ // check here. Detection: git-dir sits under .git/worktrees/<name> in a linked tree,
767
+ // while git-common-dir always points at the real .git.
768
+ isLinkedWorktree: () => {
769
+ try {
770
+ const g = (a) => execFileSync("git", ["-C", root, "rev-parse", a], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
771
+ const dir = resolve(root, g("--git-dir"));
772
+ const common = resolve(root, g("--git-common-dir"));
773
+ return dir !== common;
774
+ } catch {
775
+ return false;
776
+ }
777
+ },
778
+ // The refusal text when this checkout's remote cannot be resolved (ambiguous, or a
779
+ // `colab.remote` override naming a remote that does not exist), else null. The checks
780
+ // that read the remote's URL report it instead of passing silently (#376).
781
+ remoteProblem: () => gitRemote.remoteProblem(gitRemote.remoteInfo(root)),
782
+ // A local checkout has no labels of its own — they live on its GitHub remote, if it
783
+ // has one. Resolve the remote's slug (#376: the resolved remote, not the literal
784
+ // `origin`) and read them there; a repo with no GitHub remote returns null and
785
+ // contributes no label finding.
786
+ labels: () => {
787
+ const url = gitRemote.remoteUrl(root);
788
+ if (!url) return null;
789
+ const slug = githubSlugFromRemote(url);
790
+ return slug ? listRemoteLabels(slug) : null;
791
+ },
792
+ // #441: a release.final-grant's decision issue, on the same resolved remote as labels().
793
+ // Read only when the descriptor declares a grant; no GitHub remote = unreadable (null).
794
+ issue: (num) => {
795
+ const url = gitRemote.remoteUrl(root);
796
+ const slug = url ? githubSlugFromRemote(url) : null;
797
+ return slug ? readRemoteIssue(slug, num) : null;
798
+ },
799
+ // Same remote-slug resolution as labels() above, one API call, and only when the
800
+ // identity scan was explicitly asked for — see readRemoteMetadata for the contract.
801
+ // An unresolvable remote is its own status, not "no-remote": the scan was asked for
802
+ // and did not run, which the caller reports as a fail naming the fix.
803
+ metadata: () => {
804
+ const problem = gitRemote.remoteProblem(gitRemote.remoteInfo(root));
805
+ if (problem) return { status: "remote-unresolved", reason: problem };
806
+ const url = gitRemote.remoteUrl(root);
807
+ if (!url) return { status: "no-remote" };
808
+ const slug = githubSlugFromRemote(url);
809
+ return slug ? readRemoteMetadata(slug) : { status: "no-remote" };
810
+ },
811
+ // Every tracked `*.md` path, repo-relative — used by the anchor-link check (#158).
812
+ // git-tracked, not a filesystem walk: an untracked scratch file citing a bogus
813
+ // anchor is not a repo finding. Empty array (not null) on any failure — the
814
+ // caller's contract is "nothing to check", not "unverifiable", because a local
815
+ // checkout with no `.md` files at all is a legitimate, silent pass.
816
+ markdownFiles: () => {
817
+ try {
818
+ const out = execFileSync("git", ["-C", root, "ls-files", "*.md"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
819
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
820
+ } catch {
821
+ return [];
822
+ }
823
+ },
824
+ // Every path under a directory named `migrations` (#383's undeclared-layout check). null =
825
+ // git could not list — the check then says nothing rather than reporting a clean tree.
826
+ migrationDirFiles: () => {
827
+ try {
828
+ const out = execFileSync("git", ["-C", root, "ls-files", "--", ":(glob)**/migrations/**"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
829
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
830
+ } catch {
831
+ return null;
832
+ }
833
+ },
834
+ };
835
+ }
836
+ return {
837
+ label: target.label,
838
+ kind: "remote",
839
+ exists: true,
840
+ readFile: (p) => readRemoteFile(target.slug, p),
841
+ listDir: (p) => listRemoteDir(target.slug, p),
842
+ branches: () => listRemoteBranches(target.slug),
843
+ currentBranch: () => null,
844
+ isLinkedWorktree: () => false,
845
+ labels: () => listRemoteLabels(target.slug),
846
+ issue: (num) => readRemoteIssue(target.slug, num),
847
+ // Anchor-link check is local-only by design (#158) — enumerating markdown remotely
848
+ // would be N `gh api` calls per repo across a fleet sweep. Empty list = the check
849
+ // scans nothing and emits nothing for a remote source, matching checkRunbook's
850
+ // "would rather under-report than invent" posture for API-backed reads.
851
+ markdownFiles: () => [],
852
+ // Same cost argument as markdownFiles: a recursive tree listing per repo per sweep. null = not
853
+ // enumerated, so #383's undeclared-migration-layout check is local-only, silently.
854
+ migrationDirFiles: () => null,
855
+ tags: () => listRemoteTags(target.slug),
856
+ metadata: () => readRemoteMetadata(target.slug),
857
+ // The duration report (#137) needs a per-commit walk over historical blobs
858
+ // (`git show <sha>^:path`), which has no cheap `gh api` equivalent — reading N
859
+ // historical revisions would be N API calls per repo across a fleet sweep, the same
860
+ // cost markdownFiles() above already declined for the identical reason. A remote
861
+ // source contributes no duration finding, silently, rather than an advisory.
862
+ descriptorHistory: () => null,
863
+ fileAt: () => null,
864
+ };
865
+ }
866
+
867
+ // --------------------------------------------------------------------- self-audit
868
+ //
869
+ // The sweep covers the handbook's CONSUMERS — and the handbook itself is in the repo
870
+ // list, so it ends up asking the handbook whether it has copied the handbook. The
871
+ // answer is permanently "no", and the two stamp advisories that follow can never be
872
+ // cleared honestly: this repo's ci.yml is purpose-written rather than derived from
873
+ // templates/ci-node.yml, and its CLAUDE.md is the source the conventions block is
874
+ // extracted FROM, not a paste of it. Hand-stamping them would clear the output and
875
+ // simultaneously make the repo claim it copied itself from a version of itself —
876
+ // converting an honest advisory into a false claim, which is strictly worse than noise.
877
+ //
878
+ // Detected STRUCTURALLY, never by matching the string "colab-handbook": a fork or a
879
+ // rename must keep working, and a consumer that merely happens to carry that name must
880
+ // not inherit the exemption. Two structural facts, in order:
881
+ //
882
+ // 1. the target resolves to HANDBOOK_ROOT — the ordinary case.
883
+ // 2. the target shares a git COMMON DIR with HANDBOOK_ROOT — a linked worktree of the
884
+ // handbook is still the handbook. Sessions run from a worktree while the repo list
885
+ // names the main checkout, so a path-only test would silently miss exactly when an
886
+ // agent is looking at the output.
887
+ //
888
+ // Remote (owner/name) targets are out of scope: recognising "self" through the API would
889
+ // require the name match this deliberately avoids.
890
+
891
+ // The predicate itself now lives in tools/lib/stamp.js, shared with `colab update`. It was
892
+ // duplicated, and the copies had already drifted: this one compared git common dirs (worktree-safe)
893
+ // while the CLI's compared path strings, so the same handbook was exempt here and audited as its
894
+ // own consumer there. Only this target-shaped wrapper — kind, `~`, existence — stays local.
895
+ function isHandbookItself(target) {
896
+ if (target.kind !== "local") return false;
897
+ const raw = target.path.startsWith("~") ? join(process.env.HOME || "", target.path.slice(1)) : target.path;
898
+ const root = resolve(raw);
899
+ if (!existsSync(root)) return false;
900
+ return stamp.isHandbookItself(root, HANDBOOK_ROOT);
901
+ }
902
+
903
+ // ------------------------------------------------------------------------- checks
904
+
905
+ // §4's branch shape — both of them since #348 (`<type>/<slug>` and `<login>/<machine>/<type>/<slug>`)
906
+ // — defined once in tools/lib/branch-name.js and shared with `colab worktree new`, which emits it.
907
+ const { BRANCH_RE } = require("../tools/lib/branch-name.js");
908
+ const INTEGRATION_BRANCHES = new Set(["main", "dev", "master", "trunk"]);
909
+ // Tiers count the GATES between a merge and users: B has no production (0), C promotes and
910
+ // that promotion IS the deploy (1), A promotes to verify and a tag deploys (2). They are
911
+ // labels, not grades — C is not "worse than B"; B has no production at all.
912
+ const VALID_TIERS = new Set(["A", "B", "C"]);
913
+ const VALID_DEPLOY = new Set(["tag", "manual", "push-main", "none"]);
914
+ // `ceremony` scales memory/record-keeping DEPTH, never the safety rails (claim discipline,
915
+ // worktree isolation, reserved ports, squash + Closes #N, CI secret scan + build stay full-
916
+ // strength on every value). Omission means "standard" — no existing repo's behaviour changes
917
+ // by this field merely existing. `light` is for repos where narration has no reader (follows
918
+ // `room`, not production status — #175); the one coherence rule below (vs `autonomy:
919
+ // auto-trunk`) keeps it from drifting onto an unattended-merge repo, where an evidence trail
920
+ // is needed for a different reason than narration (project.schema.md "ceremony — optional").
921
+ const VALID_CEREMONY = new Set(["standard", "light"]);
922
+
923
+ // `writes` names which write-conflict prevention method a repo's sessions default to —
924
+ // a separate axis from both `tier` and `ceremony` (project.schema.md "writes — optional").
925
+ // Omission means "isolated", the fleet's status quo, so an unset key changes no behavior.
926
+ // #208 split the declarable value into three (`isolated` / `serial-direct` / `serial-gated`)
927
+ // and kept `serial` valid as a legacy alias — tools/lib/writes-authority.js is the ENUM
928
+ // (accepted-or-not) AND the resolution (which of the three a value means) in one shared
929
+ // module, the same split axisAuthority draws for tier -> exposure.
930
+ // `room` names who else could ever read what a session writes down — the fourth axis
931
+ // (#131). Omission means undeclared, not "solo": nothing infers this from GitHub
932
+ // visibility or anything else, and no rule reads it yet (project.schema.md "room — optional").
933
+ const VALID_ROOM = new Set(["solo", "team", "public"]);
934
+ // `exposure` names what consumes a merge here — the axis `tier`'s gate count will
935
+ // eventually be DERIVED from (#132, epic #128 axis 2). Strictly additive alongside `tier`
936
+ // in this unit: `tier` stays authoritative, and no rule here reads `exposure` to change a
937
+ // `tier`/`trunk`/`deploy`/`production` finding. Omission means undeclared, not "none" —
938
+ // exactly like `room`, and for the same reason: the only path to a value is a human
939
+ // committing the string. Nothing here infers it from GitHub visibility, `production:`,
940
+ // `tier`, or a deploy workflow (project.schema.md "exposure — optional").
941
+ const VALID_EXPOSURE = new Set(["none", "self", "live", "released"]);
942
+ // `channels` names every path by which a commit reaches something that RUNS it — a
943
+ // different question from `deploy`, which names only the trigger that promotes to
944
+ // production (#151, epic #128 §2d). Strictly additive alongside `deploy` in this unit:
945
+ // `deploy` stays authoritative, and no rule here reads `channels` to change a
946
+ // `tier`/`trunk`/`deploy`/`production` finding. A LIST, not a scalar — unlike every other
947
+ // axis here — because a repo can genuinely have several channels open at once (a deploy
948
+ // workflow AND a machine-local hook AND a tag adopters copy out of); a scalar would force
949
+ // picking the most visible one, the exact failure that produced this finding. Omission
950
+ // means undeclared, not "none" — the identical asymmetry `exposure` carries, and for the
951
+ // identical reason: only a human may write down that nothing runs this code anywhere,
952
+ // because every candidate value for an undeclared repo is a claim about an absence that
953
+ // nothing here can verify (project.schema.md "channels — optional").
954
+ const VALID_CHANNELS = new Set(["workflow", "hook", "procedure", "checkout", "artifact", "data", "none"]);
955
+ // `deploy` answers HOW a repo reaches production, never WHETHER it is tier A — the tier
956
+ // test is "does a deploy target exist today?". `manual` describes the honest third case:
957
+ // production exists, but shipping is a human running a documented runbook (rsync, compose
958
+ // up) with no workflow and no tag trigger. Before it existed, such repos had to either
959
+ // claim `tier: A, deploy: tag` (and fail the deploy-workflow rule) or claim `tier: B` and
960
+ // declare `production: null` — a lie, which §8 calls the worst outcome we can produce.
961
+ // `push-main` stays in the enum and always will: for the repos using it, a push to `main`
962
+ // GENUINELY triggers the deploy, and a project.yml that describes something other than what
963
+ // happens is the worst outcome this tool can produce (§8). It is a legitimate mechanism —
964
+ // the finding is on the combination `tier: A` + `push-main` (see the tier A block), because
965
+ // tier A's contract requires a release artifact gating production, which this shape has no
966
+ // room for. That is a mismatch with the tier, not a defect in the mechanism — and `tier: C`
967
+ // is where the mechanism fits, so the finding now has somewhere to point rather than only
968
+ // telling repos what they are not.
969
+ // NOTE: `stack` is deliberately NOT validated against a closed set. The old enum had
970
+ // no value for a Capacitor mobile app and forced one of ours to be mislabelled, so the
971
+ // enum was doing harm. It is now free-form documentation.
972
+
973
+ // ----------------------------------------------------------- exposure/channels falsifiers
974
+ //
975
+ // #137: the audit cannot CONFIRM a declared "nothing consumes this" claim (`exposure: none`
976
+ // / `channels: [none]`) — no local check can prove a negative about the outside world. What
977
+ // it CAN do is hunt for cheap repo-local artifacts that CONTRADICT the claim, the same
978
+ // falsification posture the rest of this file already takes toward tier/trunk/deploy.
979
+ //
980
+ // Severity is `warn`, never `fail`, on `exposure`'s own precedent (see the `production:`
981
+ // pairing advisory above): a falsifier proves evidence of the class that USUALLY accompanies
982
+ // a consumer, not a consumer itself — a repo released years ago and now dead is truthfully
983
+ // `exposure: none` today, tag and all. `fail` stays reserved for a descriptor contradicting
984
+ // something authoritative INSIDE itself (the tier/trunk/deploy checks above); this is
985
+ // evidence from outside the descriptor, which can misfire on a repo that is honestly
986
+ // describing its own history.
987
+ //
988
+ // Reach is deliberately 2 of 5 possible falsifiers, the two answerable from what is already
989
+ // on disk or one `gh api` call, with no per-host or cross-repo reads:
990
+ // F1 — a version-shaped tag exists (versionShapedTags, tools/lib/consumer-evidence.js).
991
+ // F5 — a committed deploy path exists: a `deploy-*`/`release-*` workflow (already
992
+ // enumerated by the tier checks — zero new IO), or a `deploy`/`release` basename
993
+ // file directly under the repo root, scripts/, or bin/ (no recursion, so a
994
+ // `templates/deploy-*.yml` — this very repo has one — or an example under docs/ is
995
+ // never mistaken for a live path).
996
+ // Three more were named in #137 and deliberately deferred, each for a reason that does not
997
+ // go away with more code:
998
+ // F2 (a per-machine service definition serves the path) — the schema already ruled this
999
+ // OUT as a field ("Per-host deploy target — deliberately not a field", project.schema.md):
1000
+ // it answers differently on every machine for the same commit, and reading outside the
1001
+ // checkout is a line this tool has never crossed.
1002
+ // F3 (another repo's stamp names this one as a source) — the stamp vocabulary today has
1003
+ // exactly one possible source, the literal string "colab-handbook", which declares
1004
+ // `exposure: released` and so could never fire on a `none` claim. Dead code until a
1005
+ // later unit generalises the stamp to name an arbitrary source.
1006
+ // F4 (a declared `production:` target resolves in DNS) — the repo-local half is already
1007
+ // BLESSED: `exposure: none` with a named `production` is the pinned-clean "visibly
1008
+ // transitional" read (CONVENTIONS.md §2, audit-exposure.test.js). Firing on it would
1009
+ // contradict a shipped ruling. The resolving half needs network, which this tool does
1010
+ // not use, and is weak evidence anyway (parked domains, wildcards, CDN catch-alls).
1011
+ // What F4 reached for — visibility into a state that has lasted a long time — is served
1012
+ // by the duration report below instead.
1013
+ //
1014
+ // `exposure: self` gets NO falsifier: `self` claims a consumer set bounded by the room
1015
+ // (CONVENTIONS.md §2, "Room"), and a tag or a deploy script is perfectly compatible with a
1016
+ // team shipping to itself — falsifying `self` needs evidence of a consumer OUTSIDE the room,
1017
+ // which none of F1/F5 are. That falsifier (if one is ever built) is out of scope here.
1018
+ //
1019
+ // Non-coupling, by construction: consumerEvidence() reads only the working tree (tags,
1020
+ // workflow filenames, root/scripts/bin listings) — it never reads `exposureRaw` or
1021
+ // `channelsRaw`. Each caller below decides independently, from its OWN key only, whether to
1022
+ // gather evidence at all; neither key's finding is used to compute the other's.
1023
+
1024
+ // VERSION_TAG_RE, versionShapedTags, DEPLOY_BASENAME_RE, consumerEvidence and describeEvidence
1025
+ // moved to tools/lib/consumer-evidence.js (#199) — install.sh freezes tools/lib/ but not audit/,
1026
+ // so `colab adopt` needed them there. Consumed above via the same createRequire this file already
1027
+ // uses for stamp.js/labels.js/axis-authority.js. No behaviour change: verified with a byte-diff of
1028
+ // `audit.mjs --local . --json` before/after the move.
1029
+
1030
+ // The raw right-hand side of a top-level `key: value` line in flat project.yml text, comment
1031
+ // stripped, or undefined when the key is absent. Deliberately not parseFlatYaml: this only
1032
+ // ever compares two revisions of the SAME key for equality (did the text change), so a raw
1033
+ // string compare is enough and a second parser implementation is not needed for it.
1034
+ function yamlRawValue(text, key) {
1035
+ const re = new RegExp(`^${key}\\s*:\\s*(.*)$`, "m");
1036
+ const m = re.exec(text || "");
1037
+ if (!m) return undefined;
1038
+ return m[1].replace(/\s+#.*$/, "").trim();
1039
+ }
1040
+
1041
+ const DURATION_MIN_DAYS = 180; // below this, silence — see audit-exposure.test.js's pinned
1042
+ // "transitional descriptor is clean" case, which this
1043
+ // threshold exists to keep passing untouched: a descriptor
1044
+ // committed moments ago must never earn a duration line.
1045
+ const DURATION_DAY_SECONDS = 86400;
1046
+
1047
+ // How long `key`'s CURRENT value has held, from the descriptor's own git history — never a
1048
+ // new field, recomputed every run. Walks descriptorHistory(key) newest -> oldest, reading
1049
+ // each commit's PARENT blob, and stops at the first commit whose parent disagreed with the
1050
+ // current value (that commit is when the current value was set). Three ways this degrades
1051
+ // to a LOWER BOUND instead of a precise date, all handled identically (return the oldest
1052
+ // commit actually inspected, marked lowerBound): the walk hits its cap without finding a
1053
+ // disagreement, the oldest matching commit's own parent blob is unreadable (a shallow
1054
+ // clone's history boundary, or the repo's root commit), or every parent inspected already
1055
+ // agreed with HEAD (the value has not changed across all of this key's tracked history).
1056
+ // Returns null — silently — when there is nothing to determine at all: no git, no matching
1057
+ // commit, or the key is not currently present (nothing to date).
1058
+ function declaredStateAge(src, key) {
1059
+ const history = src.descriptorHistory(key);
1060
+ if (!history || !history.length) return null;
1061
+
1062
+ const currentText = src.readFile(".github/project.yml");
1063
+ if (currentText === null) return null;
1064
+ const currentValue = yamlRawValue(currentText, key);
1065
+ if (currentValue === undefined) return null;
1066
+
1067
+ for (const { sha, epoch } of history) {
1068
+ const parentText = src.fileAt(`${sha}^`, ".github/project.yml");
1069
+ if (parentText === null) return { epoch, lowerBound: true }; // shallow boundary / root commit
1070
+ if (yamlRawValue(parentText, key) !== currentValue) return { epoch, lowerBound: false };
1071
+ }
1072
+ // Exhausted every matching commit (or the walk cap) without a disagreement — the value
1073
+ // has held for at least as long as the oldest inspected commit.
1074
+ return { epoch: history[history.length - 1].epoch, lowerBound: true };
1075
+ }
1076
+
1077
+ // Prose for a declaredStateAge() result, or null when it is too recent to be worth saying
1078
+ // (the DURATION_MIN_DAYS gate — the caller must check this before calling warn()).
1079
+ function renderDuration(age) {
1080
+ const days = Math.floor((Date.now() / 1000 - age.epoch) / DURATION_DAY_SECONDS);
1081
+ if (days < DURATION_MIN_DAYS) return null;
1082
+ const months = Math.floor(days / 30); // coarse on purpose — a report, not a countdown
1083
+ return `${age.lowerBound ? "at least " : ""}${months} month${months === 1 ? "" : "s"}`;
1084
+ }
1085
+
1086
+ function auditRepo(target, ctx) {
1087
+ const src = makeSource(target);
1088
+ const findings = []; // { level: 'fail'|'warn', text }
1089
+ // `self` = this target IS the handbook, not one of its consumers. Surfaced in the
1090
+ // report (and in --json) so the row reads as source-of-truth rather than clean-by-luck:
1091
+ // a silent skip is indistinguishable from a check that quietly stopped working.
1092
+ const isSelf = isHandbookItself(target);
1093
+ const info = { repo: src.label, kind: src.kind, tier: null, exposure: null, channels: null, self: isSelf, adoption: null, findings: [] };
1094
+
1095
+ const fail = (t) => findings.push({ level: "fail", text: t });
1096
+ const warn = (t) => findings.push({ level: "warn", text: t });
1097
+
1098
+ if (!src.exists) {
1099
+ fail(`path does not exist: ${target.path}`);
1100
+ return finish();
1101
+ }
1102
+
1103
+ // ---- .github/project.yml -------------------------------------------------
1104
+ const rawCfg = src.readFile(".github/project.yml");
1105
+ let cfg = null;
1106
+ if (rawCfg === null) {
1107
+ fail("no .github/project.yml — repo is undescribed (tier/trunk/deploy unknown)");
1108
+ } else {
1109
+ const { data, problems } = parseFlatYaml(rawCfg);
1110
+ problems.forEach((p) => fail(`project.yml: ${p}`));
1111
+ cfg = data;
1112
+ // `tier` is deliberately NOT in this list as of #144: it used to be the sole axis of
1113
+ // record and therefore unconditionally required, but a descriptor may now answer the
1114
+ // gate-count question with `exposure` instead — see the "axis of record" check below,
1115
+ // which fails exactly once when NEITHER key is present. `trunk`/`production`/`deploy`/
1116
+ // `stack` are unrelated to that flip and stay required unconditionally.
1117
+ const required = ["trunk", "production", "deploy", "stack"];
1118
+ // `production: null` is legal and meaningful for Tier B, so test key PRESENCE,
1119
+ // not truthiness.
1120
+ const missing = required.filter((k) => !(k in data));
1121
+ if (missing.length) fail(`project.yml: missing key(s): ${missing.join(", ")}`);
1122
+ }
1123
+
1124
+ // ---- local-only adoption (#393) -------------------------------------------
1125
+ // A repo the fleet does not own carries its descriptor in the local clone only, hidden by
1126
+ // .git/info/exclude (CONVENTIONS.md §9, "Working in a repo you don't own"). That is a real
1127
+ // adoption state, not "not adopted" — name it, and narrow the checks whose fix would be a
1128
+ // commit to the owner's repo. A descriptor untracked but NOT excluded is the accident the
1129
+ // mechanism exists to prevent: the next `git add -A` commits it into someone else's history.
1130
+ // Only a local audit can see this; a remote one reads the forge, where the file never exists.
1131
+ if (src.kind === "local") {
1132
+ info.adoption = localAdoptionState(gitDescriptorFacts(resolve(target.path), rawCfg !== null));
1133
+ if (info.adoption === "untracked") {
1134
+ warn(".github/project.yml is untracked and NOT excluded — `git status` shows it and the next `git add -A` commits it. " +
1135
+ "Commit it (an ordinary adoption), or, in a repo you don't own, hide it via .git/info/exclude (`colab adopt --local`)");
1136
+ }
1137
+ }
1138
+ const locallyAdopted = info.adoption === "local";
1139
+
1140
+ // Read once, early, so both the tier/deploy checks further down AND the exposure/
1141
+ // channels falsifiers (#137) can reuse the same listing — the falsifiers' F5 evidence
1142
+ // is explicitly "zero new IO" over what the tier checks already enumerate.
1143
+ const workflows = src.listDir(".github/workflows").filter((f) => /\.ya?ml$/.test(f));
1144
+
1145
+ const tier = cfg?.tier ?? null;
1146
+ const trunk = cfg?.trunk ?? null;
1147
+ const production = cfg?.production ?? null;
1148
+ const deploy = cfg?.deploy ?? null;
1149
+ // #144: which key is the axis of record for gate count — set inside `if (cfg)` below
1150
+ // (an unparseable/missing project.yml already fails earlier and has nothing to derive
1151
+ // from). Declared here so both halves of the decomposition — the legacy trunk-shape
1152
+ // check inside that block, and the deploy/production dispatch further down, outside it —
1153
+ // can read the same computation.
1154
+ let authority = null;
1155
+ // Omission means "standard" (#9 step 3's "no existing repo changes behavior" guarantee) —
1156
+ // so the raw value (possibly absent) is what gets validated against the enum, while the
1157
+ // defaulted value is what the coherence rules below reason from.
1158
+ const ceremonyRaw = "ceremony" in (cfg || {}) ? cfg.ceremony : null;
1159
+ const ceremony = ceremonyRaw ?? "standard";
1160
+ const autonomy = cfg?.autonomy ?? null;
1161
+ info.tier = tier;
1162
+ // Raw, no `?? default` — the load-bearing line for the "lowering exposure is a human
1163
+ // act" asymmetry (#132): there is no defaulted `exposure` variable anywhere in this
1164
+ // file, so no rule can accidentally reason from a synthesised value, and `--json`
1165
+ // reports `null` (undeclared) rather than "none" (declared: nothing consumes this).
1166
+ const exposureRaw = "exposure" in (cfg || {}) ? cfg.exposure : null;
1167
+ info.exposure = exposureRaw;
1168
+ // Raw, no `?? default` — the identical asymmetry, for the identical reason (#151):
1169
+ // `--json` reports `null` (undeclared) rather than `["none"]` (declared: nothing runs
1170
+ // this code anywhere).
1171
+ const channelsRaw = "channels" in (cfg || {}) ? cfg.channels : null;
1172
+ info.channels = channelsRaw;
1173
+ // Raw, no default — same shape as exposureRaw/channelsRaw two lines up. Declared here
1174
+ // (not inside `if (cfg)` below, where the enum-check half of this axis lives) because
1175
+ // #239's sync announcement, further down past that block, needs it too.
1176
+ const writesRaw = "writes" in (cfg || {}) ? cfg.writes : null;
1177
+
1178
+ if (cfg) {
1179
+ // Gated on presence, unlike before #144: `tier` left the `required` list above, so an
1180
+ // absent tier is no longer itself a finding here — the axis-of-record check below
1181
+ // (which runs whether or not `exposure` fills the gap) is what reports an undescribed
1182
+ // repo now. A PRESENT-but-invalid value is still reported exactly as before.
1183
+ if (tier !== null && !VALID_TIERS.has(tier)) fail(`tier is ${JSON.stringify(tier)}, expected "A", "B" or "C"`);
1184
+ if (deploy !== null && !VALID_DEPLOY.has(deploy)) fail(`deploy is ${JSON.stringify(deploy)}, expected one of: ${[...VALID_DEPLOY].join(", ")}`);
1185
+ // Only when the key exists but is blank — a wholly absent key is already
1186
+ // reported by the missing-keys check above, and saying it twice is noise.
1187
+ if ("stack" in cfg && (cfg.stack === null || cfg.stack === "")) warn("stack is empty — set a free-form string describing the stack");
1188
+ if (ceremonyRaw !== null && !VALID_CEREMONY.has(ceremonyRaw)) fail(`ceremony is ${JSON.stringify(ceremonyRaw)}, expected "standard" or "light" (omit for standard)`);
1189
+
1190
+ // ---- ceremony coherence (#79, narrowed by #175) --------------------------
1191
+ // `light` relaxes memory-ceremony DEPTH only. #175 removed the `production: null`
1192
+ // rule this used to carry: narration follows the ROOM (a live single-operator repo's
1193
+ // trail still has one reader, live or not), recoverability follows exposure and
1194
+ // irreplaceable state, and welding the two together forbade the first and was silent
1195
+ // on the second. The one guarantee left here protects anyone other than this repo's
1196
+ // own history: an unattended merge needs an evidence trail exactly when nobody
1197
+ // watched it happen.
1198
+ if (ceremony === "light") {
1199
+ if (autonomy === "auto-trunk") {
1200
+ fail(`ceremony: light is incompatible with autonomy: auto-trunk — an unattended merge with no evidence trail is a closure nobody can audit. Keep autonomy: auto-trunk and use ceremony: standard, or drop autonomy to manual`);
1201
+ }
1202
+ }
1203
+
1204
+ // ---- autonomy needs the tool it grants latitude to run (#216) -------------
1205
+ // `autonomy: auto-trunk` grants code-ship exactly one graduated exception — Phase B
1206
+ // may complete unattended, but ONLY through `colab ship`, and no other path
1207
+ // (CLAUDE.md, "One graduated exception"). A repo that declares the grant with no
1208
+ // `tools/colab` to run it with is not unsafe: nothing can act on a permission nothing
1209
+ // can invoke, so no unattended merge actually happens. But the descriptor still
1210
+ // asserts a capability the repo does not have — the same class of drift the tier +
1211
+ // deploy mismatch above reports, at `warn` rather than `fail` because nothing here is
1212
+ // a safety hazard, only a stale or aspirational field.
1213
+ if (autonomy === "auto-trunk" && src.readFile("tools/colab") === null) {
1214
+ warn(`autonomy: auto-trunk but no tools/colab in this repo — the grant has nothing to act on`);
1215
+ }
1216
+
1217
+ // ---- writes axis (#133) --------------------------------------------------
1218
+ // Deliberately NOT coupled to tier/production/exposure — see CONVENTIONS.md §2 and
1219
+ // project.schema.md. `writesRaw` itself is declared above `if (cfg)`, alongside
1220
+ // exposureRaw/channelsRaw — see that declaration's own comment for why.
1221
+ if (writesRaw !== null && !writesAuthority.isAcceptedWritesValue(writesRaw)) {
1222
+ fail(`writes is ${JSON.stringify(writesRaw)}, expected "free", "direct", or "isolated" `
1223
+ + '(the legacy spellings "serial", "serial-direct", "serial-gated" are also accepted; '
1224
+ + 'omit for free — #283)');
1225
+ }
1226
+ // #237 (⚖ Decision on #233, ruling 3): the informational replacement for the deployment-
1227
+ // shape prohibition that unit DROPPED outright ("where the trunk merge is itself the
1228
+ // deploy, keep a branch and a pre-merge gate" — no longer enforced or derived). A repo
1229
+ // needing that restriction now declares it: `writes: isolated` vetoes trunk-direct
1230
+ // outright. This is the one finding that names the veto as the remedy — the pre-existing
1231
+ // exposure/tier-legacy shape `fail`s below (both the `exposure: live` mechanism-rule path
1232
+ // and the `tier: C` + `trunk: main` legacy path) tell an adopter to move their trunk, and
1233
+ // neither mentions `writes` at all.
1234
+ //
1235
+ // MEASURED, not guessed: this can only ever fire ALONGSIDE one of those existing `fail`s —
1236
+ // `exposure: live` + `trunk: main` already fails exposure-shape's `evaluateLive`, and the
1237
+ // `tier: C` + `trunk: main` legacy path fails separately below — so it is dormant by
1238
+ // construction today (the ruling's own measurement: zero instances of this shape across 40
1239
+ // adopted descriptors). Shipped anyway per the ruling: it survives if the exposure-shape
1240
+ // rule is ever relaxed, and it is the only finding a reader sees that connects THIS shape
1241
+ // to THIS remedy. Deliberately narrow — do NOT broaden the trigger to `deploy: push-main`
1242
+ // alone, or to the tier-legacy path; that goes past what was ruled.
1243
+ const authorityForWrites = axisAuthority.axisOfRecord(cfg);
1244
+ if (
1245
+ authorityForWrites.source === "exposure" && authorityForWrites.exposure === "live"
1246
+ && trunk === "main" && !writesAuthority.trunkDirectVetoed(writesRaw)
1247
+ ) {
1248
+ warn(
1249
+ 'exposure: live with trunk "main" and no writes: isolated — here a trunk-direct commit ' +
1250
+ "reaches users immediately, because the branch a merge lands on is the branch that " +
1251
+ "deploys. Declare writes: isolated to veto trunk-direct in this repo. Informational: " +
1252
+ "this never refuses (CONVENTIONS.md §2, Writes)",
1253
+ );
1254
+ }
1255
+
1256
+ // ---- room axis (#131) ----------------------------------------------------
1257
+ // Enum sanity only — the same shape as ceremony/writes above. #131 introduces the
1258
+ // field's meaning; nothing here infers a repo's room from GitHub visibility or
1259
+ // anything else, and no downstream rule reads this value yet. A later unit may add
1260
+ // one; until it does, `room` is a declared fact this check only spell-checks.
1261
+ const roomRaw = "room" in (cfg || {}) ? cfg.room : null;
1262
+ if (roomRaw !== null && !VALID_ROOM.has(roomRaw)) fail(`room is ${JSON.stringify(roomRaw)}, expected "solo", "team" or "public" (omit if undeclared)`);
1263
+
1264
+ // ---- branchPrefix (#348) ------------------------------------------------
1265
+ // Enum sanity only, the room shape. One value today: `machine` — `colab worktree new` then cuts
1266
+ // <login>/<machine>/<type>/<slug>-<N> (CONVENTIONS.md §4). Absent = the unprefixed default.
1267
+ const prefixRaw = "branchPrefix" in (cfg || {}) ? cfg.branchPrefix : null;
1268
+ if (prefixRaw !== null && prefixRaw !== "machine") fail(`branchPrefix is ${JSON.stringify(prefixRaw)}, expected "machine" (omit for the unprefixed default)`);
1269
+
1270
+ // ---- ship-batch (#373) ------------------------------------------------------
1271
+ // Batch landing's opt-in: an integer 1–3 (tools/lib/ship-batch.js parseShipBatch — the one reading
1272
+ // `colab ship --batch` uses, so the two cannot disagree). A malformed value makes ship fail closed
1273
+ // to serial, which is safe but silent, so it fails here. Two further shapes are inert rather than
1274
+ // wrong, so they warn: no workflow fires on a `ship-batch/**` push (the combined run can never
1275
+ // arrive), and no `autonomy: auto-trunk` (a batch lands in one unattended push, which needs it).
1276
+ if ("ship-batch" in (cfg || {}) && cfg["ship-batch"] !== null) {
1277
+ const sbCfg = shipBatch.parseShipBatch(cfg);
1278
+ if (!sbCfg.valid) fail(sbCfg.reason);
1279
+ else if (sbCfg.n > 1) {
1280
+ const firing = workflowsFiringOnBranchPush({ readFile: (p) => src.readFile(p), workflows, branch: shipBatch.PROBE_REF });
1281
+ if (!firing.length) warn(`ship-batch: ${sbCfg.n} but no workflow in .github/workflows fires on a push to ship-batch/** — colab ship --batch will always fall back to serial; add 'ship-batch/**' to a CI workflow's push: branches:`);
1282
+ if (autonomy !== "auto-trunk") warn(`ship-batch: ${sbCfg.n} is inert without autonomy: auto-trunk — colab ship --batch lands every member in one unattended push`);
1283
+ }
1284
+ }
1285
+
1286
+ // ---- migrations (#383) ----------------------------------------------------
1287
+ // Where the repo's migrations live, beyond the two defaults (database/migrations/,
1288
+ // prisma/migrations/) — tools/lib/migration-paths.js is the one reading, shared with
1289
+ // `colab ship`'s no-new-migrations gate and `release cut`'s schema-additive check, so the
1290
+ // three cannot disagree. An invalid entry fails: ship reads it leniently only in the stricter
1291
+ // direction, and a declaration nobody can trust is not an answer. Redundancy only warns.
1292
+ // Then the half no declaration can answer for itself: a tracked `*/migrations/` directory
1293
+ // that NO rule covers is most likely a layout the gate cannot see — the exact shape that let
1294
+ // a production backfill read `no new migrations ✓`. Advisory: a `docs/migrations/` guide is
1295
+ // a false positive, and only a human can tell the two apart. Local-only (see migrationDirFiles).
1296
+ const migCfg = migrationPaths.parseMigrationPaths(cfg);
1297
+ migCfg.problems.forEach((p) => fail(p));
1298
+ migCfg.notes.forEach((p) => warn(p));
1299
+ const migFiles = src.migrationDirFiles();
1300
+ if (migFiles) {
1301
+ const undeclared = migrationPaths.undeclaredMigrationDirs(migFiles, migCfg.paths);
1302
+ if (undeclared.length) {
1303
+ warn(`migration-shaped director${undeclared.length === 1 ? "y" : "ies"} outside every declared path: ${undeclared.join(", ")} — colab ship's no-new-migrations gate does not see ${undeclared.length === 1 ? "it" : "them"}; declare in project.yml (migrations: [${undeclared.join(", ")}]) if these are migrations`);
1304
+ }
1305
+ }
1306
+
1307
+ // ---- migration-grant (#398) -----------------------------------------------
1308
+ // Who may open the no-new-migrations door: `human` (absent — today's behaviour) or `reviewer`.
1309
+ // A flat key, deliberately NOT nested under `migrations:` (that stays a list of path prefixes,
1310
+ // read by three consumers). tools/lib/migration-grant.js parseGrantPolicy is the one reading, so
1311
+ // `colab migration-grant` and the audit cannot disagree. The value is always reported
1312
+ // (info.migrationGrant). An invalid value fails: the reader falls back to `human`, which is safe
1313
+ // but silent. `reviewer` is clean: colab ship honours it under P+M+HEAD+R (#401).
1314
+ {
1315
+ const pol = migrationGrant.parseGrantPolicy(cfg);
1316
+ info.migrationGrant = pol.policy;
1317
+ if (!pol.valid) fail(pol.reason);
1318
+ }
1319
+
1320
+ // ---- trust-humans (#407) --------------------------------------------------
1321
+ // Which logins count as HUMAN for a grant or a ruling. Absent = the association class, as
1322
+ // before. tools/lib/trust-humans.js parseTrustHumans is the one reading. A malformed value
1323
+ // fails: the reader then treats NOBODY as human (fail closed), which blocks every human grant
1324
+ // until fixed — loud here rather than discovered at the next migration ship.
1325
+ {
1326
+ const tr = trustHumansLib.parseTrustHumans(cfg);
1327
+ info.trustHumans = tr.declared && tr.valid ? [...tr.humans] : null;
1328
+ if (!tr.valid) fail(tr.reason);
1329
+ }
1330
+
1331
+ // ---- live-env (#403) ------------------------------------------------------
1332
+ // `live-env: none` is the one declaration that skips code-wrap A3's hermetic second test run
1333
+ // (`colab gate-hermetic`). tools/lib/hermetic.js parseLiveEnv is the one reading. An invalid
1334
+ // value fails: the reader treats it as absent (the stricter direction — the run still happens),
1335
+ // so the declaration silently does nothing, and a declaration nobody can trust is not an answer.
1336
+ {
1337
+ const le = hermeticLib.parseLiveEnv(cfg);
1338
+ info.liveEnv = le.declared ? le.value : null;
1339
+ if (!le.valid) fail(le.reason);
1340
+ }
1341
+
1342
+ // ---- gate (#410) ----------------------------------------------------------
1343
+ // Local = a fast smoke check, branch CI = the one authoritative gate. tools/lib/gate.js
1344
+ // parseGate is the one reading. An invalid block fails: the reader falls back to the local full
1345
+ // gate, so the declaration silently does nothing. `authoritative: ci` with no workflow firing on
1346
+ // a feature-branch push warns: the verdict can never arrive, so every reader stays on local.
1347
+ {
1348
+ const gt = gateLib.parseGate(cfg);
1349
+ info.gate = gt.declared && gt.valid ? { smoke: gt.smoke, authoritative: gt.authoritative } : null;
1350
+ if (!gt.valid) fail(gt.reason);
1351
+ else if (gt.authoritative === "ci") {
1352
+ const firing = workflowsFiringOnBranchPush({ readFile: (p) => src.readFile(p), workflows, branch: gateLib.PROBE_REF });
1353
+ if (!firing.length) warn("gate: authoritative ci but no workflow in .github/workflows fires on a push to a feature branch — branch CI can never arrive, so code-wrap and code-ship stay on the local full gate; add a push: branches trigger covering session branches");
1354
+ }
1355
+ }
1356
+
1357
+ // ---- holds (#360) ---------------------------------------------------------
1358
+ // Shape only: the labels this repo's scheduler treats as start holds, read by code-triage
1359
+ // so its READY list matches what the scheduler would start (CONVENTIONS.md §5, Holds). A
1360
+ // malformed value would be read as "no holds declared" — held work then reports ready — so
1361
+ // every shape defect is a fail. Whether the labels exist on the tracker is not checked.
1362
+ if ("holds" in (cfg || {}) && cfg.holds !== null) {
1363
+ const holdsRaw = cfg.holds;
1364
+ if (!Array.isArray(holdsRaw)) {
1365
+ fail(`holds is ${JSON.stringify(holdsRaw)}, expected a list of label names (e.g. [needs-rescope]) — a bare scalar is not a valid shape`);
1366
+ } else if (holdsRaw.some((h) => typeof h !== "string" || h.trim() === "")) {
1367
+ fail(`holds contains an empty or non-string member (${JSON.stringify(holdsRaw)}) — each member is one label name`);
1368
+ } else if (new Set(holdsRaw).size !== holdsRaw.length) {
1369
+ fail(`holds contains a duplicate member (${JSON.stringify(holdsRaw)}) — list each label once: ${JSON.stringify([...new Set(holdsRaw)])}`);
1370
+ }
1371
+ }
1372
+
1373
+ // ---- exposure axis (#132) -------------------------------------------------
1374
+ // Enum sanity, plus exactly one pairing advisory — the same restrained shape as
1375
+ // room/writes above. `tier` stays authoritative in this unit; nothing here changes
1376
+ // any tier/trunk/deploy/production finding, and no rule couples exposure to tier
1377
+ // (CONVENTIONS.md §2 "Exposure", project.schema.md "exposure — optional": "do not add
1378
+ // one" mirrors the writes axis's own instruction, for the same reason).
1379
+ if (exposureRaw !== null && !VALID_EXPOSURE.has(exposureRaw)) {
1380
+ fail(`exposure is ${JSON.stringify(exposureRaw)}, expected one of: none, self, live, released (omit if undeclared)`);
1381
+ }
1382
+ // The one case that asserts BOTH "nothing consumes this" AND "there is nothing to
1383
+ // point at" — advisory, not a failure: the descriptor isn't lying (nothing here can
1384
+ // verify absence of a consumer), it's unanswered, and answering it is a human act
1385
+ // (#128 ruling) this unit does not perform. A `fail` here would make declaring the
1386
+ // key riskier than omitting it, which would suppress exactly the opt-in adoption data
1387
+ // a later unit needs.
1388
+ if (exposureRaw === "none" && (production === null || production === "")) {
1389
+ warn(`exposure: none and production: null — either nothing is left to reach here, or nobody has answered the exposure question yet. Both read the same to this tool; a human should confirm which`);
1390
+ }
1391
+ // ---- exposure falsifier + duration report (#137) --------------------------
1392
+ // Gated on the raw value alone — `self`/`live`/`released`/undeclared never reach here,
1393
+ // so an outside adopter who has not opted into this axis does no new IO at all. See the
1394
+ // "exposure/channels falsifiers" block above for the full argument (severity, the 2-of-5
1395
+ // reach, why `self` gets nothing here).
1396
+ if (exposureRaw === "none") {
1397
+ const evidenceLine = describeEvidence(consumerEvidence(src, workflows));
1398
+ if (evidenceLine) {
1399
+ warn(
1400
+ `exposure: none is contradicted by repo evidence — ${evidenceLine}. This does not ` +
1401
+ `prove a live consumer (a repo released years ago and now dead is truthfully ` +
1402
+ `exposure: none) — it means the claim is worth a second look, not that it is wrong`,
1403
+ );
1404
+ }
1405
+ const exposureAge = declaredStateAge(src, "exposure");
1406
+ const durationLine = exposureAge && renderDuration(exposureAge);
1407
+ if (durationLine) {
1408
+ warn(`exposure: none has held for ${durationLine} (per the descriptor's own git history) — visible so a long-running transitional state does not go unnoticed`);
1409
+ }
1410
+ }
1411
+
1412
+ // ---- release: block (#337) -------------------------------------------------
1413
+ // Gated on the key's presence: a descriptor with no `release:` does no work here and
1414
+ // gets no finding — its policy is the default §6's release rung derives from exposure +
1415
+ // deploy, which `colab release cut` (#338) reads through the same module. A declared
1416
+ // block may narrow that default and never widen it; every widening attempt, bad value
1417
+ // or unknown sub-key is a `fail`, because a silently ignored widening would make the
1418
+ // rung's human gate a suggestion.
1419
+ if ("release" in cfg) {
1420
+ const rel = releasePolicy.evaluateRelease(cfg);
1421
+ for (const f of rel.findings) {
1422
+ if (f.level === "fail") fail(f.text);
1423
+ else warn(f.text);
1424
+ }
1425
+ // #441: `final: auto` on deploy-tag stands only on an operator's grant, and the grant is a
1426
+ // tracker fact — the decision issue it names must carry a recorded, trusted ruling that has
1427
+ // not been reopened. Unreadable fails closed: an automatic production deploy nobody can
1428
+ // trace to a human's choice is exactly what the grant exists to rule out.
1429
+ const grant = rel.effective.finalGrant;
1430
+ if (grant) {
1431
+ const v = releasePolicy.finalGrantVerdict(src.issue ? src.issue(grant.issue) : null, { issue: grant.issue, trust: trustHumansLib.parseTrustHumans(cfg) });
1432
+ info.releaseFinalGrant = { issue: grant.issue, ok: v.ok, ruledBy: v.ruledBy };
1433
+ if (!v.ok) fail(`release.final: auto on deploy-tag has no resolvable operator grant — ${v.detail} (CONVENTIONS.md §6, An operator-granted automatic final)`);
1434
+ }
1435
+ }
1436
+
1437
+ // ---- channels axis (#151) -------------------------------------------------
1438
+ // Shape + enum sanity, a descriptor-internal coherence advisory, and — when the shape is
1439
+ // exactly `[none]` — the repo-evidence falsifier and duration report (#137, wired below,
1440
+ // gated on `channelsRaw` alone so it never reads `exposureRaw`). `deploy` stays
1441
+ // authoritative in this unit; nothing here changes any tier/trunk/deploy/production
1442
+ // finding, and no rule couples `channels` to `exposure` (CONVENTIONS.md §2 "Channels",
1443
+ // project.schema.md "channels — optional": deliberately not paired, mirroring the writes
1444
+ // axis's own "do not add one" instruction).
1445
+ if (channelsRaw !== null) {
1446
+ if (!Array.isArray(channelsRaw)) {
1447
+ fail(`channels is ${JSON.stringify(channelsRaw)}, expected a list (e.g. [workflow]) — a bare scalar is not a valid shape`);
1448
+ } else if (channelsRaw.length === 0) {
1449
+ fail(`channels is an empty list — that is not an answer; declare [none] if nothing runs this code anywhere, or omit the key if undeclared`);
1450
+ } else {
1451
+ const unknown = channelsRaw.filter((c) => !VALID_CHANNELS.has(c));
1452
+ const deduped = [...new Set(channelsRaw)];
1453
+ if (unknown.length) {
1454
+ fail(`channels contains ${JSON.stringify(unknown)}, expected members of: ${[...VALID_CHANNELS].join(", ")}`);
1455
+ } else if (deduped.length !== channelsRaw.length) {
1456
+ // #197's second ruling: a duplicate member (even of an otherwise-valid value, e.g.
1457
+ // `[workflow, workflow]`) previously passed silently — only `[none, none]` was ever
1458
+ // caught, and only incidentally, via the exclusivity check below. Same severity as
1459
+ // every other shape rule in this block (`fail`): a duplicate is a malformed answer,
1460
+ // not a real one, same class as the empty-list and unknown-member cases above.
1461
+ fail(`channels contains a duplicate member (${JSON.stringify(channelsRaw)}) — declare each channel once: ${JSON.stringify(deduped)}`);
1462
+ } else if (channelsRaw.includes("none") && channelsRaw.length > 1) {
1463
+ fail(`channels combines "none" with another value (${JSON.stringify(channelsRaw)}) — "none" means nothing runs this code anywhere and must stand alone`);
1464
+ } else if (
1465
+ channelsRaw.length === 1 &&
1466
+ channelsRaw[0] === "none" &&
1467
+ ((production !== null && production !== "") || (deploy !== null && deploy !== "none"))
1468
+ ) {
1469
+ // The one advisory: "nothing runs this code anywhere" against a fact already
1470
+ // authoritative elsewhere in the same descriptor that says otherwise. `warn`,
1471
+ // never `fail`, on exposure's precedent — a `fail` would make declaring the key
1472
+ // riskier than omitting it.
1473
+ warn(`channels: [none] together with production: ${JSON.stringify(production)} / deploy: ${JSON.stringify(deploy)} — either nothing actually runs this code, or channels was declared before the rest of the descriptor was; a human should confirm which`);
1474
+ }
1475
+
1476
+ // ---- channels falsifier + duration report (#137) --------------------
1477
+ // Gated on the validated shape alone (length 1, "none") — a standalone check, not a
1478
+ // branch of the if/else-if chain above, but the condition alone already implies
1479
+ // `unknown` is empty and nothing else is combined with "none" ("none" is a member of
1480
+ // VALID_CHANNELS and length 1 excludes the multi-value case). See the "exposure/
1481
+ // channels falsifiers" block above for the full argument.
1482
+ if (channelsRaw.length === 1 && channelsRaw[0] === "none") {
1483
+ const evidenceLine = describeEvidence(consumerEvidence(src, workflows));
1484
+ if (evidenceLine) {
1485
+ warn(
1486
+ `channels: [none] is contradicted by repo evidence — ${evidenceLine}. This does ` +
1487
+ `not prove a live consumer — it means the claim is worth a second look, not that ` +
1488
+ `it is wrong`,
1489
+ );
1490
+ }
1491
+ const channelsAge = declaredStateAge(src, "channels");
1492
+ const durationLine = channelsAge && renderDuration(channelsAge);
1493
+ if (durationLine) {
1494
+ warn(`channels: [none] has held for ${durationLine} (per the descriptor's own git history) — visible so a long-running transitional state does not go unnoticed`);
1495
+ }
1496
+ }
1497
+ }
1498
+ }
1499
+
1500
+ // ---- axis of record (#144) -----------------------------------------------
1501
+ // Which key governs gate count: `exposure` when declared (it wins outright — see
1502
+ // tools/lib/axis-authority.js for why this is a function, not a bijection, of `tier`),
1503
+ // else a LEGACY read derived from `tier` (byte-identical to pre-#144 behaviour for every
1504
+ // descriptor that has not declared `exposure`), else neither — the one new hard failure
1505
+ // this unit adds, replacing the old unconditional "missing key(s): tier".
1506
+ authority = axisAuthority.axisOfRecord(cfg);
1507
+ if (authority.source === "none") {
1508
+ fail("project.yml: no axis of record — neither tier nor exposure is declared. Set one (CONVENTIONS.md §2)");
1509
+ } else if (authority.tier !== null && VALID_TIERS.has(authority.tier) && authority.source === "exposure") {
1510
+ // Both declared. Consistent -> silent (no nag to delete `tier`; carrying both is fine
1511
+ // and this repo's own descriptor models exactly that). Inconsistent -> exactly one
1512
+ // fail naming the disagreement; the `exposure` branch below still enforces afterward.
1513
+ const disagreement = axisAuthority.contradiction(authority.tier, authority.exposure);
1514
+ if (disagreement) fail(disagreement);
1515
+ }
1516
+ // The one new advisory this unit ships, and it is dormant today: activates only once
1517
+ // the HANDBOOK ITSELF (not this repo's stamp) reaches AUTHORITY_FLIP_VERSION, mirroring
1518
+ // the `hb.untagged` precedent `compareStamp` already uses elsewhere in this file. Gated
1519
+ // on `tier-legacy` only — a repo that already declared `exposure` has nothing to be
1520
+ // nudged about.
1521
+ if (
1522
+ authority.source === "tier-legacy" &&
1523
+ !ctx.handbook.untagged && ctx.handbook.hasGit &&
1524
+ cmpSemver(ctx.handbook.version, stamp.AUTHORITY_FLIP_VERSION) >= 0
1525
+ ) {
1526
+ warn(
1527
+ `exposure is undeclared — tier is now read as a LEGACY value (tier ${authority.tier} -> ` +
1528
+ `exposure: ${authority.exposure ?? "null"}) rather than the axis of record. Declare ` +
1529
+ `exposure: explicitly to opt in (CONVENTIONS.md §2)`,
1530
+ );
1531
+ }
1532
+
1533
+ // ---- tier <-> trunk coherence, legacy voice ------------------------------
1534
+ // Runs ONLY on the `tier-legacy` path (no `exposure` declared) and is otherwise
1535
+ // UNCHANGED from before #144 — this is the half of the decomposition that must stay
1536
+ // byte-identical for every descriptor without `exposure` (#144's primary oracle). The
1537
+ // canonical Tier A shape is the dev/main split — sessions land on dev, main is the
1538
+ // release branch — which buys a place for the expensive suite to run at promotion time.
1539
+ // But a TAG-GATED A may run a SINGLE trunk `main`: when a version tag gates production,
1540
+ // the tag itself marks the release boundary, so a second branch marking the same
1541
+ // boundary (dev vs main) is redundant. The tier is defined by the promotion GATE (a
1542
+ // deliberate release artifact — the tag), not the trunk NAME, so `main` is coherent here
1543
+ // — and ONLY here. `deploy: manual`/`push-main` have no tag to mark the boundary, so
1544
+ // they keep the dev split and its promotion as the ship-ward act.
1545
+ if (authority.source === "tier-legacy") {
1546
+ if (tier === "A" && trunk !== "dev" && !(deploy === "tag" && trunk === "main")) {
1547
+ fail(deploy === "tag"
1548
+ ? `tier A with deploy: tag requires trunk "dev" or "main", found ${JSON.stringify(trunk)}`
1549
+ : `tier A requires trunk "dev", found ${JSON.stringify(trunk)} — only a tag-gated A (deploy: tag) may run a single trunk "main"`);
1550
+ }
1551
+ if (tier === "B" && trunk !== "main") fail(`tier B requires trunk "main", found ${JSON.stringify(trunk)}`);
1552
+ // C uses A's two-branch split: main = what is live, trunk = where sessions land. #205:
1553
+ // this validates the SPLIT, not the spelling — trunk is a declared setting (default
1554
+ // "dev", proposed by colab adopt and the templates), never required to literally be
1555
+ // "dev". The one thing that must hold is that trunk is NOT main itself, since main is
1556
+ // the release branch the promotion deploys — collapsing the two would remove the only
1557
+ // moment anyone decides to ship. A declared name other than "dev" is conforming, not
1558
+ // exempted (CONVENTIONS.md §2, project.schema.md "trunk — required").
1559
+ if (tier === "C" && (!trunk || trunk === "main")) fail(`tier C requires trunk to be a branch distinct from "main" (the release branch the promotion deploys), found ${JSON.stringify(trunk)} — "dev" is the default trunk name; any other declared name is equally conforming (CONVENTIONS.md §2)`);
1560
+ }
1561
+ }
1562
+
1563
+ // Additive `--json` keys only (#144's oracle: "`tier` continues to report the DECLARED
1564
+ // letter... New keys are additive"). `axisOfRecord` names which key governs
1565
+ // ('exposure' | 'tier-legacy' | 'none' | null when project.yml itself did not parse);
1566
+ // `gates` is the gate count that resolves to, when known.
1567
+ info.axisOfRecord = authority ? authority.source : null;
1568
+ info.gates = authority && authority.exposure ? (axisAuthority.GATE_COUNT[authority.exposure] ?? null) : null;
1569
+
1570
+ // ---- convention labels present on the tracker ---------------------------
1571
+ // A convention label absent from an adopted repo is a check that can never fire: the
1572
+ // claim (`in-progress`) cannot land, the readiness column (`deps-checked`) can never
1573
+ // leave "nobody looked", provenance (`agent-filed`) reads every filed issue as human-
1574
+ // approved. It happens when a repo adopted at an OLDER handbook version, before a label
1575
+ // entered the set, and nothing back-filled it — so a repo missing the label passes clean
1576
+ // while a downstream board keeps advising "run triage to fill the column", a no-op.
1577
+ // Gated on `cfg`: an undescribed repo already fails above, and labels are meaningless
1578
+ // without adoption. `labels()` is null for a remote-less or offline audit (see
1579
+ // listRemoteLabels) — we stay silent there, since we cannot assert a label is missing
1580
+ // when we could not read the set. A warn, not a fail: the fix is one `colab labels
1581
+ // --ensure` (#206), it breaks no build and it does not make the descriptor lie.
1582
+ if (cfg) {
1583
+ const labels = src.labels();
1584
+ // #376: an unresolvable remote is not "offline" — the operator can fix it in one command, and
1585
+ // staying silent would read as a clean label set. Reported, never guessed. Same warn level.
1586
+ const remoteProblem = !labels && src.remoteProblem ? src.remoteProblem() : null;
1587
+ if (remoteProblem) warn(`convention labels: not checked — ${remoteProblem}`);
1588
+ if (labels) {
1589
+ // #393: a locally adopted repo owes only the load-bearing subset — the rest is opt-in by use
1590
+ // on a tracker the fleet does not own.
1591
+ const inScope = (n) => !locallyAdopted || MINIMAL_LABEL_NAMES.includes(n);
1592
+ const missing = missingConventionLabels(labels).filter(inScope);
1593
+ if (missing.length && locallyAdopted) {
1594
+ warn(`missing load-bearing label(s): ${missing.join(", ")} — a locally adopted repo needs only ` +
1595
+ `${MINIMAL_LABEL_NAMES.join(", ")}. Run \`colab labels --ensure --minimal\``);
1596
+ } else if (missing.length) {
1597
+ warn(
1598
+ `missing convention label(s): ${missing.join(", ")} — a repo adopted before a ` +
1599
+ `label entered the set never back-filled it, so the check it powers can never ` +
1600
+ `fire. Run \`colab labels --ensure\` to back-fill the whole set`,
1601
+ );
1602
+ }
1603
+ // #364: the reverse gap. `--ensure` never overwrites an existing label, so a label
1604
+ // created before the handbook reworded it keeps the old description forever and the
1605
+ // tracker states a meaning the handbook has since changed. Same warn-not-fail reasoning
1606
+ // as above. It cannot tell older wording from a declared local divergence (CONVENTIONS.md
1607
+ // §8, Upstream) — that is a reading of both texts, which the fix command's own report
1608
+ // prints; this line only makes the difference visible.
1609
+ const stale = staleConventionDescriptions(labels).filter((d) => inScope(d.name));
1610
+ if (stale.length) {
1611
+ warn(
1612
+ `convention label description(s) differ from the handbook's: ` +
1613
+ `${stale.map((d) => d.name).join(", ")} — \`colab labels --ensure\` never rewrites ` +
1614
+ `an existing label, so a reworded meaning never reached this tracker. Run ` +
1615
+ `\`colab labels --ensure\` to see both texts, then \`--refresh-descriptions\` ` +
1616
+ `(\`--keep <name>\` for a declared local divergence)`,
1617
+ );
1618
+ }
1619
+ }
1620
+ }
1621
+
1622
+ // ---- CLAUDE.md is a router, not an archive (#64) -------------------------
1623
+ // Unconditional: this is a repo-doc concern, not a tier/deploy one, and it applies to
1624
+ // the handbook's OWN CLAUDE.md too (not a stamp check, so it is not gated on !isSelf).
1625
+ checkClaudeMdSize(src, warn);
1626
+ // #417: same posture — a tool block loaded twice, or the Conventions block moved out of the
1627
+ // file tools look it up in, is a repo-doc concern on every repo, the handbook's own included.
1628
+ checkInstructionFileBlocks(src, warn);
1629
+ // #419: and prose left in CLAUDE.md / no AGENTS.md at all — same posture, same reason.
1630
+ checkInstructionFileShape(src, warn);
1631
+
1632
+ // ---- markdown anchor links resolve (#158) --------------------------------
1633
+ // Unconditional, same posture as checkClaudeMdSize above: general markdown hygiene,
1634
+ // not a stamp/tier concern, applies to the handbook's own docs unchanged. A `§N`
1635
+ // prose citation is invisible to this on purpose — only an actual `](file#slug)`
1636
+ // link is checked, so the ~280 not-yet-migrated citations produce zero findings.
1637
+ checkAnchorLinks(src, fail);
1638
+
1639
+ // ---- deploy workflow presence -------------------------------------------
1640
+ const deployWorkflows = workflows.filter((f) => /^deploy[-.]/.test(f));
1641
+ checkPrereleaseTagTrigger(src, workflows, deploy, fail, warn);
1642
+ checkReleaseAuto(src, workflows, cfg, warn);
1643
+ checkPrivateNpm(src, workflows, fail, warn);
1644
+
1645
+ const runbook = cfg && "runbook" in cfg ? cfg.runbook : null;
1646
+
1647
+ // ---- gate contract, dispatched by axis of record (#144) ------------------
1648
+ // `authority` is null only when project.yml itself did not parse (already failed above,
1649
+ // nothing to derive from). `tier-legacy` runs the UNCHANGED tier-voiced block — the half
1650
+ // that must stay byte-identical for every descriptor without `exposure`. `exposure` runs
1651
+ // the new exposure-voiced rules below: the DECOMPOSITION #144's plan calls for. No branch
1652
+ // in the exposure-voiced half ever reads `tier` — proof the split was cut in the right
1653
+ // place. `none` (no axis of record at all) already got its one fail above; there is
1654
+ // nothing further to derive a gate contract from.
1655
+ if (authority && authority.source === "tier-legacy") {
1656
+ if (tier === "A") {
1657
+ // The answer to "how does this reach production?" must be committed. A CI-driven deploy commits
1658
+ // it as an in-repo deploy-*.yml; a deploy that runs OUTSIDE CI must instead be WRITTEN DOWN in a
1659
+ // runbook: — the same invariant, honoured two ways. Two shapes deploy outside CI:
1660
+ // - deploy: manual → a human runs the runbook.
1661
+ // - deploy: tag with no workflow → an EXTERNAL deployer (a GitOps poller fast-forwards a
1662
+ // release branch on the tag, or the like) ships it; the
1663
+ // runbook documents that path. A deploy: tag repo whose own
1664
+ // CI holds the deploy job keeps its deploy-*.yml and needs no
1665
+ // runbook — the workflow already commits the answer.
1666
+ const externalTagDeploy = deploy === "tag" && !deployWorkflows.length;
1667
+ if (deploy === "manual") {
1668
+ checkRunbook(src, runbook, fail, warn, "deploy: manual");
1669
+ } else if (externalTagDeploy) {
1670
+ checkRunbook(src, runbook, fail, warn, "deploy: tag deployed outside CI (an external GitOps poller)");
1671
+ } else if (!deployWorkflows.length) {
1672
+ fail("tier A but no .github/workflows/deploy-*.yml — the path to production is not in the repo (use deploy: manual + runbook: if it ships by hand, or deploy: tag + runbook: when a GitOps poller deploys the tag from outside CI)");
1673
+ }
1674
+ if (production === null || production === "") fail("tier A but production is null — set the live URL, or drop to tier B");
1675
+ if (deploy === "none") fail('tier A with deploy: none is contradictory — use "tag" or "manual"');
1676
+ // A TIER MISMATCH, not a bad mechanism. push-main is a perfectly good way to deploy;
1677
+ // it just cannot satisfy tier A's contract, which is that a deliberate release artifact
1678
+ // gates production. Here every push to main reaches users, so that gate does not exist.
1679
+ // The message says "options include" on purpose: the two named exits are not exhaustive
1680
+ // and must not read as though they were.
1681
+ if (deploy === "push-main") {
1682
+ fail(
1683
+ "tier A with deploy: push-main — tier A's contract is that a deliberate release " +
1684
+ "artifact gates production, and here every push to main reaches users with no such " +
1685
+ "gate. Options include: retier to C (tier C is exactly this shape — promotion IS the " +
1686
+ "deploy — and is the honest home for a live, low-stakes site), migrate the pipeline " +
1687
+ "to a tag trigger (deploy: tag), or — if shipping really is run by hand — " +
1688
+ "deploy: manual plus runbook: naming the committed procedure.",
1689
+ );
1690
+ }
1691
+ } else if (tier === "C") {
1692
+ // C = "promotion IS the deploy": one gate (the dev→main merge) stands between a merge and
1693
+ // users. It exists because a tag ritual nobody honours is worse than no tag ritual — a
1694
+ // live low-stakes site had nowhere honest to sit, so it claimed A and failed A's contract.
1695
+ if (production === null || production === "") fail("tier C but production is null — tier C is for repos that ARE live; set the live URL, or drop to tier B");
1696
+ if (!deployWorkflows.length) fail("tier C but no .github/workflows/deploy-*.yml — the path to production is not in the repo");
1697
+ // C is defined by its mechanism: the promotion itself deploys. Any other `deploy` value
1698
+ // describes a DIFFERENT number of gates, which is a different tier — so each wrong value
1699
+ // is redirected to the tier that actually matches it, rather than being merely rejected.
1700
+ if (deploy !== "push-main") {
1701
+ if (deploy === "tag") {
1702
+ fail('tier C with deploy: tag — a tag gating production is tier A\'s shape (promotion verifies, the tag deploys = two gates). If you really have a tag ritual, you are tier A; if the tag is aspirational, drop it and use deploy: push-main');
1703
+ } else if (deploy === "manual") {
1704
+ fail('tier C with deploy: manual — there the promotion does NOT deploy (a human running the runbook does), which is tier A with deploy: manual. Retier to A, or use deploy: push-main if the promotion itself ships');
1705
+ } else if (deploy === "none") {
1706
+ fail('tier C with deploy: none is contradictory — tier C means the promotion deploys. Use deploy: push-main, or drop to tier B if nothing is live');
1707
+ } else {
1708
+ fail(`tier C requires deploy: push-main, found ${JSON.stringify(deploy)} — C is defined as "promotion IS the deploy"`);
1709
+ }
1710
+ }
1711
+ } else if (tier === "B") {
1712
+ // This was silently unchecked before: a tier B repo that actually deploys is
1713
+ // either mistiered or shipping to production with none of the tier A gates.
1714
+ if (deploy !== null && deploy !== "none") fail(`tier B must have deploy: none, found ${JSON.stringify(deploy)} — if this really deploys, retier: C when the promotion itself ships, A when a tag or a runbook gates it`);
1715
+ if (production !== null && production !== "") fail(`tier B must not declare a production URL, found ${JSON.stringify(production)} — retier to C (promotion deploys) or A (a tag/runbook gates the deploy)`);
1716
+ if (deployWorkflows.length) fail(`tier B but a deploy workflow exists (${deployWorkflows.join(", ")}) — retier to C or A, or delete it`);
1717
+ }
1718
+ } else if (authority && authority.source === "exposure") {
1719
+ const exp = authority.exposure; // already enum-validated above: none | self | live | released | garbage
1720
+ const hasProduction = production !== null && production !== "";
1721
+
1722
+ // The ONE piece of this axis that stays hand-authored here rather than in the shared table
1723
+ // (#207, tools/lib/exposure-shape.js): `warn`, deliberately never `fail` (#144's plan,
1724
+ // "rulings") — raising exposure by proposing `released` ahead of the evidence that would
1725
+ // confirm it is the direction an agent may propose, and a `fail` would make declaring the
1726
+ // key riskier than omitting it, punishing exactly the adoption this axis exists to invite.
1727
+ // `colab adopt`'s constructor (EXPOSURE_SHAPE, now exposureShapeVerdict) never blocks on
1728
+ // this either — it is advisory on both sides, so there was never a second copy to unify.
1729
+ if (exp === "released" && !hasProduction) {
1730
+ const hasArtifactEvidence = versionShapedTags(src.tags()).length > 0 || (Array.isArray(channelsRaw) && channelsRaw.includes("artifact"));
1731
+ if (!hasArtifactEvidence) {
1732
+ warn(
1733
+ "exposure: released with production: null and no evidence of a release artifact " +
1734
+ "(no version-shaped git tag, no channels: [artifact]) — either the evidence has not " +
1735
+ "landed yet, or this should read exposure: self/none for now. Both look the same to " +
1736
+ "this tool; a human should confirm which",
1737
+ );
1738
+ }
1739
+ }
1740
+
1741
+ // Every mechanism/contract rule (self/none/live/released) is the ONE shared table (#207,
1742
+ // tools/lib/exposure-shape.js) — `colab adopt`'s constructor reads the identical table to
1743
+ // decide whether a NEW declaration is supported at all. `self` yields no entries by
1744
+ // construction (CONVENTIONS.md §2: no mechanism rule applies to it, not even trunk shape).
1745
+ // A `runbook`-kind entry defers to `checkRunbook` here (this file can read the repo and tell
1746
+ // "missing" from "unreadable via the API"); every other entry is a ready `fail` message.
1747
+ const shapeCtx = { trunk, hasProduction, deploy, hasDeployWorkflow: deployWorkflows.length > 0, deployWorkflowNames: deployWorkflows };
1748
+ for (const entry of evaluateExposure(exp, shapeCtx)) {
1749
+ if (entry.kind === "runbook") checkRunbook(src, runbook, fail, warn, entry.why);
1750
+ else fail(entry.message);
1751
+ }
1752
+ }
1753
+
1754
+ // ---- declared trunk actually exists -------------------------------------
1755
+ const branches = src.branches();
1756
+ if (trunk && branches === null) {
1757
+ warn(`cannot list branches (not a git checkout, or gh unavailable) — trunk "${trunk}" unverified`);
1758
+ } else if (trunk && branches && !branches.includes(trunk)) {
1759
+ fail(`declared trunk "${trunk}" does not exist (branches: ${branches.slice(0, 6).join(", ")}${branches.length > 6 ? ", …" : ""})`);
1760
+ }
1761
+
1762
+ // ---- the main checkout is on trunk at rest -------------------------------
1763
+ // Other things read a repo's working tree — a dev server, a symlink, a LaunchAgent —
1764
+ // and none of them know a session branched it. We branched one repo's main checkout
1765
+ // for a chore; it ran always-on from that tree, so the live app served unmerged
1766
+ // feature-branch code until a human noticed by eye. Sessions belong in a worktree;
1767
+ // a checkout parked on a feature branch is the failure, not the work.
1768
+ // Remote (owner/name) targets have no checkout, so currentBranch() is null there —
1769
+ // stay silent rather than invent a violation, as with `branches === null` above.
1770
+ //
1771
+ // Decision (#204): only fire when trunk has (or had) a LOCAL ref here. `git clone
1772
+ // --branch main` of a conforming Tier A/C repo legitimately leaves the checkout on
1773
+ // "main" with trunk ("dev") existing only as `origin/dev` — that checkout was never on
1774
+ // trunk, so "return the checkout to dev" is not advice, it is noise: there is nothing to
1775
+ // return it to. A checkout that once had trunk locally and has since drifted onto
1776
+ // another branch is the actual failure this check exists for, so that case still fires
1777
+ // exactly as before — the branch-existence fix above (union with refs/remotes) is
1778
+ // deliberately NOT reused here; `localBranches()` keeps the local/remote distinction
1779
+ // this specific decision turns on.
1780
+ const head = src.currentBranch();
1781
+ const localBranches = src.localBranches ? src.localBranches() : null;
1782
+ const trunkEverLocal = Array.isArray(localBranches) && localBranches.includes(trunk);
1783
+ if (trunk && head && head !== "HEAD" && head !== trunk && !src.isLinkedWorktree() && trunkEverLocal) {
1784
+ fail(`main checkout is on "${head}", not trunk "${trunk}" — anything reading this working tree (dev server, symlink, LaunchAgent) is serving that branch. Move the work to a worktree and return the checkout to ${trunk}`);
1785
+ }
1786
+
1787
+ // ---- integration lines (optional, dev-side only) -------------------------
1788
+ // A declared long-lived line that worktrees may be cut from and shipped back into. It is NOT a
1789
+ // second trunk: nothing in the promote / tag / deploy path reads this field, which is what keeps
1790
+ // such a line unable to reach production BY CONSTRUCTION rather than by discipline. The tier↔trunk
1791
+ // coherence check above is deliberately untouched — relaxing `trunk:` was the rejected design,
1792
+ // because on tiers A and C trunk IS the branch promotion consumes.
1793
+ const integration = checkIntegration(cfg, trunk, branches, fail, warn);
1794
+ // Declared lines are integration points, so they inherit trunk's exemptions: the §4 branch-name
1795
+ // regex does not apply to them, and a workflow naming one is not referencing a ghost.
1796
+
1797
+ // ---- release branch (optional, production-side, opposite axis from integration) ----
1798
+ // Names the branch an EXTERNAL GitOps poller fast-forwards on tag, in the single-trunk
1799
+ // tag-gated shape (trunk: main). Unlike integration lines this is a PRODUCTION ref — it
1800
+ // grants no worktree base, nothing here adds it to allowedBases() — but it needs the same
1801
+ // naming-regex and ghost-branch exemptions integration lines get, for the same reason: it
1802
+ // is a long-lived name a workflow or a human may reasonably reference. Its real payoff is
1803
+ // in `colab doctor` (tools/colab), which otherwise reads it as a spent branch between
1804
+ // releases and advises deleting a live deploy target (#63).
1805
+ const releaseBranch = checkReleaseBranch(cfg, trunk, branches, fail, warn, deploy);
1806
+
1807
+ // ---- owner's branch (optional, #394) ----
1808
+ // A repo the fleet builds in but does not own may name the owner's branch; trunk stays the
1809
+ // fleet's integration branch and the owner's branch is reached only by a PR he merges
1810
+ // (`colab deliver`). Gated on the key's presence — no key, no work, no finding. It may not
1811
+ // collide with anything a colab command pushes to.
1812
+ for (const f of ownerBranchLib.evaluate(cfg, { trunk, integration, releaseBranch, branches: Array.isArray(branches) ? branches : null })) {
1813
+ if (f.level === "fail") fail(f.text);
1814
+ else warn(f.text);
1815
+ }
1816
+ const ownerDeclared = ownerBranchLib.read(cfg);
1817
+ const ownerExempt = ownerDeclared.branch && !ownerDeclared.problems.length ? [ownerDeclared.branch] : [];
1818
+ const exemptList = [...integration, ...(releaseBranch ? [releaseBranch] : []), ...ownerExempt];
1819
+ const exempt = exemptList.length ? new Set([...INTEGRATION_BRANCHES, ...exemptList]) : INTEGRATION_BRANCHES;
1820
+
1821
+ // ---- branch naming -------------------------------------------------------
1822
+ // Deliberately LOCAL branches only, not the refs/remotes-inclusive `branches` union above
1823
+ // (#204). "Does trunk exist" and "is a workflow's trigger a ghost" are existence
1824
+ // questions, where a remote-only branch is as real as a local one. Naming convention is a
1825
+ // different question — it is about what THIS checkout's own history has produced — and
1826
+ // widening it to every branch that has ever touched the remote pulls in every worktree
1827
+ // session, past or present, from every machine and every collaborator: measured against
1828
+ // the live fleet, that turned a quiet advisory into a double-digit list on several repos,
1829
+ // none of it actionable from here. `localBranches()` is null for a remote (owner/name)
1830
+ // target (no local checkout to have local refs), so that case still falls back to the
1831
+ // full API list `branches()` already gave it — unaffected by this distinction, exactly as
1832
+ // before this fix.
1833
+ const branchesForNaming = localBranches !== null ? localBranches : branches;
1834
+ if (branchesForNaming) {
1835
+ const bad = branchesForNaming.filter((b) => !exempt.has(b) && !BRANCH_RE.test(b));
1836
+ if (bad.length) {
1837
+ warn(`branch name(s) off-convention: ${bad.slice(0, 4).join(", ")}${bad.length > 4 ? ` (+${bad.length - 4})` : ""} — want <type>/<slug>, or <login>/<machine>/<type>/<slug> (CONVENTIONS.md §4)`);
1838
+ }
1839
+ }
1840
+
1841
+ // ---- trunk is CI-gated ---------------------------------------------------
1842
+ // Merges land on the trunk as PUSHES; if no CI workflow triggers on push to the
1843
+ // declared trunk, every merge runs zero CI while everyone believes it is gated.
1844
+ // #393: in a locally adopted repo the workflows are the OWNER's — gating the fleet's integration
1845
+ // branch would be a commit to his repo — so an ungated trunk is an advisory there, not a failure.
1846
+ // It is still stated, because it is not cosmetic: `colab ship` reads "no run at trunk's head" as
1847
+ // human-gated, so every ship onto that branch will need a ci-granted exemption.
1848
+ const trunkCiFail = locallyAdopted
1849
+ ? (t) => warn(`${t} — locally adopted: the workflows are the owner's, so this is not yours to fix by commit, but every \`colab ship\` onto it stays human-gated (ci-granted) until a workflow runs there`)
1850
+ : fail;
1851
+ checkTrunkCiGated(src, trunk, workflows, branches, trunkCiFail, warn, { integration, exempt });
1852
+
1853
+ // ---- toolchain agreement -------------------------------------------------
1854
+ // Report disagreement; never auto-resolve. Three sources can disagree: the
1855
+ // descriptor, the ecosystem manifest, and what the workflows actually pin.
1856
+ const tool = collectToolchain(src, cfg, workflows);
1857
+ tool.findings.forEach((f) => findings.push(f));
1858
+
1859
+ // ---- handbook reconciliation (stamps) -----------------------------------
1860
+ // EXEMPTION, not suppression, and scoped by CONSTRUCTION: a single guarded STATEMENT
1861
+ // rather than `if (!isSelf) { … }`, so a check somebody adds next to this one cannot
1862
+ // silently inherit the exemption by landing inside the block. The handbook is not
1863
+ // exempt from its own rules — every check above runs on it unchanged — it is exempt
1864
+ // only from being audited as its own consumer.
1865
+ //
1866
+ // Note this is narrower than it may look: one of our Python+Node hybrids emits the
1867
+ // SAME two advisory lines, legitimately (its ci.yml really is an unstamped copy).
1868
+ // Identical text, opposite meanings — nothing here may generalise to that row.
1869
+ // ---- adoption compatibility window (#138) --------------------------------
1870
+ // An old descriptor must report as PREDATING this version, never as broken — reusing
1871
+ // the stamp machinery already above rather than a new mechanism. Missing axes are
1872
+ // "undeclared" on every repo (#131/#132/#133/#151's own asymmetry: never a default,
1873
+ // never nagged on their own); this adds exactly one extra fact when a repo's CLAUDE
1874
+ // stamp names a handbook version at which those axes did not yet exist in
1875
+ // project.schema.md — the marker is not lying, it is simply from before the question
1876
+ // was ever asked.
1877
+ const missingAxes = cfg ? stamp.AXES.filter((a) => !(a in cfg)) : [];
1878
+ info.predatesAxes = [];
1879
+ if (!isSelf) checkStamps(src, ctx.handbook, ctx.templateNames, fail, warn, { ceremony, missingAxes, predatesAxes: info.predatesAxes, writesRaw });
1880
+
1881
+ // ---- repository metadata identity scan (#228 part 4) ----------------------
1882
+ // Explicitly NOT gated on isSelf: the handbook is public, its description and topics are
1883
+ // read by every visitor, and it is subject to the rule it publishes.
1884
+ if (ctx.identity) checkIdentityMetadata(src, ctx.identity, info, fail);
1885
+
1886
+ function finish() {
1887
+ info.findings = findings;
1888
+ info.ok = !findings.some((f) => f.level === "fail");
1889
+ info.clean = findings.length === 0;
1890
+ return info;
1891
+ }
1892
+ return finish();
1893
+ }
1894
+
1895
+ /**
1896
+ * #228 part 4 — the identity scan of REPOSITORY METADATA: name, description, homepage and
1897
+ * topics. None of it passes through git, so the pre-commit scan cannot see any of it, and it
1898
+ * is the first thing a visitor reads.
1899
+ *
1900
+ * SCOPED TO PUBLIC REPOS. The harm this answers is publication: a hostname in a private
1901
+ * repo's description is visible to the people who already have the repo. A private repo is
1902
+ * therefore NOT APPLICABLE — a determination, reached by successfully reading `visibility`,
1903
+ * which is a different thing from a check that could not run and must not be reported the
1904
+ * same way.
1905
+ *
1906
+ * FAIL DIRECTION. `unreadable` is a `fail`, not a warn and never silence. The operator passed
1907
+ * --identity, so a repo whose metadata could not be read is a scan that did not happen, and
1908
+ * the one outcome that must never be possible is a sweep reporting clean over a check that
1909
+ * never ran. This is deliberately stricter than the labels check next door, which stays
1910
+ * silent on the same failure: nothing there was asked for, and an unreadable label set costs
1911
+ * a provisioning nag rather than a missed disclosure.
1912
+ *
1913
+ * REDACTION. A hit prints the field and the vocabulary entry number, never the matched text.
1914
+ * The audit's output is pasted into issues and chat far more often than a hook's is, so
1915
+ * republishing the string in a finding ABOUT that string is the one thing this must not do.
1916
+ * COLAB_IDENTITY_SHOW=1 unredacts locally, the same lever the hook uses.
1917
+ *
1918
+ * Writes `info.identityMetadata` on every path, including the silent ones, so `--json`
1919
+ * always states what happened even where the text report says nothing.
1920
+ */
1921
+ function checkIdentityMetadata(src, vocab, info, fail) {
1922
+ const meta = src.metadata ? src.metadata() : { status: "unreadable" };
1923
+
1924
+ if (meta.status === "no-remote") {
1925
+ info.identityMetadata = { status: "not-applicable", reason: "no GitHub remote — no repository metadata exists" };
1926
+ return;
1927
+ }
1928
+ if (meta.status === "remote-unresolved") {
1929
+ info.identityMetadata = { status: "unreadable", reason: meta.reason };
1930
+ fail(`repository metadata: ${meta.reason} — the identity scan did NOT run`);
1931
+ return;
1932
+ }
1933
+ if (meta.status !== "ok" || !meta.data) {
1934
+ info.identityMetadata = { status: "unreadable" };
1935
+ fail("repository metadata: could not be read through `gh` (offline, unauthenticated, or no such repo) — the identity scan did NOT run");
1936
+ return;
1937
+ }
1938
+
1939
+ const data = meta.data;
1940
+ const isPublic = data.visibility ? data.visibility === "public" : data.private === false;
1941
+ if (!isPublic) {
1942
+ info.identityMetadata = { status: "not-applicable", reason: "repository is not public" };
1943
+ return;
1944
+ }
1945
+
1946
+ const records = [];
1947
+ if (data.name) records.push({ location: "repository name", text: String(data.name) });
1948
+ if (data.description) records.push({ location: "description", text: String(data.description) });
1949
+ if (data.homepage) records.push({ location: "homepage", text: String(data.homepage) });
1950
+ for (const [i, topic] of (Array.isArray(data.topics) ? data.topics : []).entries()) {
1951
+ records.push({ location: `topic ${i + 1}`, text: String(topic) });
1952
+ }
1953
+
1954
+ const hits = identity.scan(records, vocab.terms);
1955
+ if (!hits.length) {
1956
+ info.identityMetadata = { status: "clean", fields: records.length };
1957
+ return;
1958
+ }
1959
+
1960
+ const show = process.env.COLAB_IDENTITY_SHOW === "1";
1961
+ info.identityMetadata = {
1962
+ status: "matched",
1963
+ fields: records.length,
1964
+ // The report carries the same redaction as the text output — see the note above.
1965
+ hits: hits.map((h) => ({ location: h.location, entry: h.entry, chars: h.chars, ...(show ? { value: h.value } : {}) })),
1966
+ };
1967
+ for (const hit of hits) {
1968
+ fail(`repository metadata names something the identity vocabulary forbids — ${identity.describeHit(hit, { show })}`);
1969
+ }
1970
+ }
1971
+
1972
+ // `integration:` — the declared dev-side axis. Optional; absent is the normal case.
1973
+ //
1974
+ // It answers one question: which OTHER long-lived branches may a worktree legitimately be cut from
1975
+ // and shipped back into? A team keeping a line for a release months out otherwise has nowhere to put
1976
+ // it, and the two available workarounds are both worse: park the main checkout on it (the exact
1977
+ // state the on-trunk check exists to catch — everything reading that working tree serves the line),
1978
+ // or declare it as `trunk` (which points the promotion path at it, since on tiers A and C trunk is
1979
+ // what promotion consumes).
1980
+ //
1981
+ // The validity rules all defend the same boundary — that a declared line is a DEVELOPMENT
1982
+ // integration point and can never be a production one:
1983
+ // - not `trunk`: trunk is already the primary integration point; listing it twice would give the
1984
+ // same branch two sets of rules, one of which reaches production.
1985
+ // - not `main`: on tiers A and C that is the release branch, and on tier B it is trunk. Either way
1986
+ // it is the branch this field must never touch.
1987
+ // - not literally `trunk`: a branch by that name is banned outright (§2 — trunk is a role).
1988
+ // - it must EXIST: a declared line nobody cut is the "release branch nothing consumes" failure
1989
+ // under a new name, and the CLI would cut worktrees from a ref that is not there.
1990
+ //
1991
+ // Returns the validated list (possibly empty) so callers can exempt these branches from the
1992
+ // naming regex and the ghost-branch advisory.
1993
+ function checkIntegration(cfg, trunk, branches, fail, warn) {
1994
+ if (!cfg || !("integration" in cfg)) return [];
1995
+ const raw = cfg.integration;
1996
+ if (raw === null) return []; // `integration:` with nothing under it — an empty list, the default
1997
+ if (!Array.isArray(raw)) {
1998
+ fail(`integration must be a list of branch names, found ${JSON.stringify(raw)} — write it as "- <branch>" lines or [a, b]`);
1999
+ return [];
2000
+ }
2001
+ const out = [];
2002
+ for (const entry of raw) {
2003
+ const b = entry === null || entry === undefined ? "" : String(entry).trim();
2004
+ if (!b) { fail("integration contains an empty entry"); continue; }
2005
+ if (b === trunk) {
2006
+ fail(`integration lists the trunk ("${b}") — trunk is already the primary integration point; the field is for ADDITIONAL lines`);
2007
+ continue;
2008
+ }
2009
+ if (b === "main") {
2010
+ fail('integration lists "main" — that is the release branch (tiers A and C) or the trunk (tier B), and nothing on this axis may have a path to production');
2011
+ continue;
2012
+ }
2013
+ if (b === "trunk") {
2014
+ fail('integration lists "trunk" — "trunk" is a role, never a branch name (CONVENTIONS.md §2)');
2015
+ continue;
2016
+ }
2017
+ if (out.includes(b)) { warn(`integration lists "${b}" twice`); continue; }
2018
+ out.push(b);
2019
+ }
2020
+ if (Array.isArray(branches)) {
2021
+ for (const b of out) {
2022
+ if (!branches.includes(b)) fail(`integration line "${b}" does not exist as a branch — a declared line nobody cut is the same failure as a release branch nothing consumes`);
2023
+ }
2024
+ } else if (out.length) {
2025
+ warn(`cannot list branches — integration line(s) ${out.join(", ")} unverified`);
2026
+ }
2027
+ return out;
2028
+ }
2029
+
2030
+ // `releaseBranch:` — the declared external-deploy axis. Optional; absent is the normal case, and
2031
+ // most Tier A repos deploy from `main` itself and need no extra name.
2032
+ //
2033
+ // It answers a different question from `integration:`, on the opposite side of the fence: which
2034
+ // branch does an EXTERNAL GitOps poller fast-forward on release, in the single-trunk tag-gated
2035
+ // shape (`trunk: main`, `deploy: tag`)? That branch is, by construction, an ancestor of trunk
2036
+ // between releases — the release script fast-forwarded it to trunk's tip as of the last tag, and
2037
+ // trunk has moved on since — which reads identically to a spent session branch to any check that
2038
+ // reasons from ancestry alone. `colab doctor` is exactly that kind of check (tools/colab), and
2039
+ // undeclared it prints a ready-to-paste delete command for a ref a live deploy pipeline is
2040
+ // polling (#63). Declaring it here is what lets doctor tell the two apart.
2041
+ //
2042
+ // The validity rules mirror checkIntegration's, because both defend a declared name actually
2043
+ // meaning something — but the axis itself is inverted: this field is scoped to touch nothing
2044
+ // BUT production (a worktree may never be cut from it or ship into it), where integration's
2045
+ // whole guarantee is to never touch production at all.
2046
+ // - not `trunk`: this field names a THIRD branch, distinct from trunk and from `main` — the
2047
+ // single-trunk tag-gated shape already treats `main` as the release artifact's landing spot.
2048
+ // - not `main`: same branch, same reasoning, stated for the same "fail closed on a malformed
2049
+ // descriptor" reason integration's check states it.
2050
+ // - not literally `trunk`: banned outright, same as everywhere (§2 — trunk is a role).
2051
+ // - it must EXIST: a declared branch nobody cut is the identical failure this field exists to
2052
+ // name — "a release branch nothing consumes" — just reached from the descriptor side instead
2053
+ // of doctor's ancestry side.
2054
+ //
2055
+ // Returns the validated branch name, or "" (never a list — a repo has at most one).
2056
+ function checkReleaseBranch(cfg, trunk, branches, fail, warn, deploy) {
2057
+ if (!cfg || !("releaseBranch" in cfg)) return "";
2058
+ const raw = cfg.releaseBranch;
2059
+ if (raw === null) return ""; // `releaseBranch:` with nothing under it — same as absent
2060
+ if (Array.isArray(raw) || (typeof raw === "object" && raw !== null)) {
2061
+ fail(`releaseBranch must be a single branch name, found ${JSON.stringify(raw)} — a repo has at most one`);
2062
+ return "";
2063
+ }
2064
+ const b = String(raw).trim();
2065
+ if (!b) { fail("releaseBranch is set but empty"); return ""; }
2066
+ if (b === trunk) {
2067
+ fail(`releaseBranch names the trunk ("${b}") — it must name a DIFFERENT branch than trunk (the single-trunk tag-gated shape already lands day-to-day work on trunk itself)`);
2068
+ return "";
2069
+ }
2070
+ if (b === "main") {
2071
+ fail('releaseBranch is "main" — that is trunk itself in the single-trunk tag-gated shape this field targets; name the separate branch the external poller actually watches');
2072
+ return "";
2073
+ }
2074
+ if (b === "trunk") {
2075
+ fail('releaseBranch is "trunk" — "trunk" is a role, never a branch name (CONVENTIONS.md §2)');
2076
+ return "";
2077
+ }
2078
+ if (Array.isArray(branches)) {
2079
+ if (!branches.includes(b)) {
2080
+ fail(`releaseBranch "${b}" does not exist as a branch — a declared release branch nobody cut is the same failure as a release branch nothing consumes`);
2081
+ return "";
2082
+ }
2083
+ } else {
2084
+ warn(`cannot list branches — releaseBranch "${b}" unverified`);
2085
+ }
2086
+ // Advisory, not a failure: the field's only meaning is a tag fast-forwarding this branch, so a
2087
+ // repo declaring it under any other `deploy:` is very likely describing a shape that does not
2088
+ // exist yet, or that has already changed underneath the descriptor.
2089
+ if (deploy !== "tag") {
2090
+ warn(`releaseBranch "${b}" is declared but deploy is ${JSON.stringify(deploy)} — this field only means something for deploy: tag (an external poller fast-forwarding it on release)`);
2091
+ }
2092
+ return b;
2093
+ }
2094
+
2095
+ // `CLAUDE.md` is the router (code-wrap A2), loaded in full into EVERY session before any
2096
+ // work starts — together with every in-repo file it @-imports (#417: a thin-shell CLAUDE.md
2097
+ // that imports AGENTS.md is measured as the whole loaded set, not as the shell alone). Issue #64: A2's rule was prose-only, and its own worst-case citation is
2098
+ // framed in LINES — which is structurally blind to the failure that actually occurred. A
2099
+ // repo audited clean at 197 lines carried 112,382 bytes because a single "pointer" row had
2100
+ // grown into a hand-maintained paraphrase of the whole document it was meant to point at:
2101
+ // 68,350 bytes, 60.8% of the file, 9.3x the next-largest row. Because CLAUDE.md sits in the
2102
+ // cached prompt PREFIX, that cost is paid on every TURN of every session, not once per
2103
+ // session — a byte ceiling on the whole file catches the aggregate, and a per-LINE ceiling
2104
+ // catches the specific signature: one physical line ballooning while nothing else grows.
2105
+ //
2106
+ // Deliberately NOT scoped to markdown table rows: a repo that routes with a bullet list
2107
+ // (`- docs/x.md — one line`) carries the identical risk if one bullet's line balloons, and
2108
+ // scanning physical lines catches both shapes without assuming either.
2109
+ //
2110
+ // Both thresholds are WARN, not FAIL. The issue that proposed them offered the numbers "as
2111
+ // a starting point rather than a recommendation", wanting calibration across adopting repos
2112
+ // before anything here becomes a hard gate — the goal is a finding with the measured number
2113
+ // ("state the condition"), not a build-breaking assertion of a still-uncalibrated one.
2114
+ const CLAUDE_MD_MAX_BYTES = 40 * 1024; // near the handbook's own cited worst case (39 KB / 452 lines)
2115
+ const CLAUDE_MD_LINE_MULTIPLE = 6; // "some small multiple of the [file's] median row"
2116
+ const CLAUDE_MD_LINE_ABS_FLOOR = 2048; // below this, flagging on multiple alone is noise (tiny medians make everything look huge)
2117
+
2118
+ // #117: the byte ceiling above was built to catch hand-written accretion, but it counts
2119
+ // TOTAL file bytes — which also charges a repo for content it cannot shorten by the rule's
2120
+ // own logic: a derived block (e.g. a generated table of contents a script rebuilds from
2121
+ // another doc's headings) that a test elsewhere asserts matches byte-for-byte. That content
2122
+ // grows by construction, one line per source fact, and editing it by hand to "fix" the
2123
+ // advisory makes the repo's OWN gate red. A repo following the router rule perfectly still
2124
+ // gets charged for adopting a pattern the handbook prefers.
2125
+ //
2126
+ // The fix: let a repo mark a span as derived, and gate the advisory on AUTHORED bytes
2127
+ // (total minus every marked span) instead of total. Total is still reported — a file that
2128
+ // is mostly derived is still fully loaded into every session, and that cost stays visible —
2129
+ // but only authored bytes decide whether the finding fires. `id=` is required so a repo
2130
+ // with more than one generated block (e.g. a TOC and a changelog) can have both.
2131
+ const DERIVED_START_RE = /^<!--\s*colab:derived:start\s+id=(\S+)\s*-->\s*$/;
2132
+ const DERIVED_END_RE = /^<!--\s*colab:derived:end\s*-->\s*$/;
2133
+
2134
+ /**
2135
+ * Splits `text` into `{ authoredLines, derivedBytes, malformed }`. `authoredLines` holds
2136
+ * every physical line (marker lines included, since they are structural annotations, not
2137
+ * prose) EXCEPT lines inside a well-formed derived span. `malformed` lists any marker
2138
+ * problem (unterminated start, stray end, nested start) — on malformed input we fail open:
2139
+ * the offending span and everything after its unmatched marker is treated as AUTHORED, so a
2140
+ * broken marker never hides real prose from the advisory it exists to inform.
2141
+ */
2142
+ function splitDerivedSpans(text) {
2143
+ const lines = text.split(/\r?\n/);
2144
+ const authoredLines = [];
2145
+ const malformed = [];
2146
+ let openId = null;
2147
+ let spanLines = [];
2148
+
2149
+ for (const line of lines) {
2150
+ if (openId === null) {
2151
+ const m = line.match(DERIVED_START_RE);
2152
+ if (m) {
2153
+ openId = m[1];
2154
+ spanLines = [line];
2155
+ continue;
2156
+ }
2157
+ if (DERIVED_END_RE.test(line)) {
2158
+ malformed.push(`a colab:derived:end with no matching start`);
2159
+ authoredLines.push(line); // stray end — keep it, it's just text at that point
2160
+ continue;
2161
+ }
2162
+ authoredLines.push(line);
2163
+ } else {
2164
+ if (DERIVED_START_RE.test(line)) {
2165
+ malformed.push(`nested colab:derived:start (id=${openId} was still open)`);
2166
+ // Fail open: treat the whole thing-so-far as authored and stop tracking a span.
2167
+ authoredLines.push(...spanLines, line);
2168
+ openId = null;
2169
+ spanLines = [];
2170
+ continue;
2171
+ }
2172
+ spanLines.push(line);
2173
+ if (DERIVED_END_RE.test(line)) {
2174
+ openId = null; // well-formed span closes; its lines are NOT authored
2175
+ spanLines = [];
2176
+ }
2177
+ }
2178
+ }
2179
+
2180
+ if (openId !== null) {
2181
+ malformed.push(`colab:derived:start id=${openId} was never closed`);
2182
+ authoredLines.push(...spanLines); // fail open — count the unterminated span as authored
2183
+ }
2184
+
2185
+ return { authoredLines, malformed };
2186
+ }
2187
+
2188
+ // Minimal GitHub-compatible heading→anchor slugifier (#158). GitHub's real algorithm is
2189
+ // unpublished; this is deliberately the common-case subset, calibrated against the 47
2190
+ // anchor links already live in this repo (CLAUDE.md, CONVENTIONS.md, README*.md,
2191
+ // project.schema.md, skills/handbook-sync/SKILL.md, tools/README.md) — every one of
2192
+ // them resolves under it. Not a general markdown-heading parser: it does not need to be,
2193
+ // because the only headings it is ever asked to slugify are the ones already governing
2194
+ // the links this check exists to validate.
2195
+ function slugifyHeading(text) {
2196
+ return text
2197
+ .replace(/`([^`]*)`/g, "$1") // code spans contribute their literal text, not backticks
2198
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") // [text](url) contributes only the text
2199
+ .trim()
2200
+ .replace(/#+$/, "") // a trailing "##" some repos use to mark a self-anchor
2201
+ .toLowerCase()
2202
+ // strip punctuation, keep Unicode letters/digits, underscore, hyphens/spaces -- NOT
2203
+ // collapsed. `\w` is ASCII-only ([A-Za-z0-9_]); GitHub's real slugifier keeps Unicode
2204
+ // letters (Vietnamese, Japanese, accented Latin, ...), so `\w` alone silently deleted
2205
+ // them and produced a slug GitHub never renders (#280). `\p{L}`/`\p{N}` (with the `/u`
2206
+ // flag) widen letter/digit matching to Unicode while `_` stays its own explicit member
2207
+ // of the class -- it must NOT be folded into `\p{L}`/`\p{N}`, because the very next
2208
+ // step below (`.replace(/[ _]/g, "-")`) turns underscores into hyphens and needs them
2209
+ // to survive this line to do it; the issue's own one-line suggestion dropped `_` from
2210
+ // the class and would have silently broken every underscored heading slug.
2211
+ .replace(/[^\p{L}\p{N}_\- ]+/gu, "")
2212
+ .trim()
2213
+ // Each space/underscore becomes its OWN hyphen -- never collapsed. GitHub does not
2214
+ // merge runs: a heading like "tier -- required" strips the em-dash but keeps both
2215
+ // spaces around where it was, producing "tier--required" (double hyphen), and every
2216
+ // link already written against a real heading in this repo is punctuated that way.
2217
+ // Collapsing here silently breaks every one of them.
2218
+ .replace(/[ _]/g, "-");
2219
+ }
2220
+
2221
+ // Every heading in `text`, in document order, mapped to its resolved slug — including
2222
+ // GitHub's duplicate-slug suffixing (`-1`, `-2`, … in heading order, not alphabetical).
2223
+ // Fenced code blocks are skipped so a `#` inside a code sample is never read as a heading.
2224
+ function collectHeadingSlugs(text) {
2225
+ const slugs = new Set();
2226
+ const seen = new Map(); // base slug -> next suffix to try
2227
+ let inFence = false;
2228
+ for (const line of text.split("\n")) {
2229
+ if (/^\s*(```|~~~)/.test(line)) { inFence = !inFence; continue; }
2230
+ if (inFence) continue;
2231
+ const m = /^#{1,6}\s+(.+?)\s*$/.exec(line);
2232
+ if (!m) continue;
2233
+ const base = slugifyHeading(m[1]);
2234
+ if (!base) continue;
2235
+ const n = seen.get(base) ?? 0;
2236
+ seen.set(base, n + 1);
2237
+ slugs.add(n === 0 ? base : `${base}-${n}`);
2238
+ }
2239
+ return slugs;
2240
+ }
2241
+
2242
+ // Every `](target#fragment)` markdown link, repo-relative to the file that carries it.
2243
+ // `target` is `""` for a same-file link (`[…](#slug)`); anything already resolved by the
2244
+ // caller. Deliberately link-shaped ONLY — a bare `§N` in prose, or a bare `FILE.md#slug`
2245
+ // mention with no `[...](...)` around it, is not a citation this check may touch (#158's
2246
+ // whole scope boundary: the ~280 un-migrated `§N` citations must be invisible to this).
2247
+ const ANCHOR_LINK_RE = /\]\(([^)#\s]*\.md)?#([^)\s]+)\)/g;
2248
+
2249
+ // Blanks out fenced code blocks and inline `code spans` before the link scan runs, so a
2250
+ // doc that shows link syntax as a LITERAL EXAMPLE (this very file does, documenting this
2251
+ // very check) is never mistaken for a real citation. Same fence-skip as
2252
+ // collectHeadingSlugs, plus a same-line inline-span strip; not a full markdown parser,
2253
+ // just enough to keep a documented example from tripping the thing it documents.
2254
+ function stripCodeForLinkScan(text) {
2255
+ const out = [];
2256
+ let inFence = false;
2257
+ for (const line of text.split("\n")) {
2258
+ if (/^\s*(```|~~~)/.test(line)) { inFence = !inFence; out.push(""); continue; }
2259
+ out.push(inFence ? "" : line.replace(/`[^`\n]*`/g, ""));
2260
+ }
2261
+ return out.join("\n");
2262
+ }
2263
+
2264
+ // Levenshtein edit distance, local and dependency-free (#187) — the check's suggestion
2265
+ // list needs a real similarity measure to earn the word "nearest" in its message; plain
2266
+ // two-row DP is all that's warranted at the scale of a heading slug, no need to optimise.
2267
+ function levenshtein(a, b) {
2268
+ const m = a.length;
2269
+ const n = b.length;
2270
+ let prev = new Array(n + 1);
2271
+ let curr = new Array(n + 1);
2272
+ for (let j = 0; j <= n; j++) prev[j] = j;
2273
+ for (let i = 1; i <= m; i++) {
2274
+ curr[0] = i;
2275
+ for (let j = 1; j <= n; j++) {
2276
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
2277
+ curr[j] = Math.min(
2278
+ prev[j] + 1, // deletion
2279
+ curr[j - 1] + 1, // insertion
2280
+ prev[j - 1] + cost, // substitution
2281
+ );
2282
+ }
2283
+ [prev, curr] = [curr, prev];
2284
+ }
2285
+ return prev[n];
2286
+ }
2287
+
2288
+ function checkAnchorLinks(src, fail) {
2289
+ if (src.kind !== "local") return; // remote enumeration is O(files) gh API calls — skip, not warn (see markdownFiles())
2290
+ const files = src.markdownFiles();
2291
+ const headingCache = new Map(); // repo-relative path -> Set<slug> | null (null = unreadable)
2292
+
2293
+ const slugsFor = (path) => {
2294
+ if (headingCache.has(path)) return headingCache.get(path);
2295
+ const text = src.readFile(path);
2296
+ const result = text === null ? null : collectHeadingSlugs(text);
2297
+ headingCache.set(path, result);
2298
+ return result;
2299
+ };
2300
+
2301
+ for (const file of files) {
2302
+ const text = src.readFile(file);
2303
+ if (text === null) continue; // listed by git but unreadable — not this check's concern
2304
+ const dir = dirname(file);
2305
+ let m;
2306
+ ANCHOR_LINK_RE.lastIndex = 0;
2307
+ const scanText = stripCodeForLinkScan(text);
2308
+ while ((m = ANCHOR_LINK_RE.exec(scanText))) {
2309
+ const [, rawTarget, fragment] = m;
2310
+ const line = scanText.slice(0, m.index).split("\n").length;
2311
+ // An external target is not a repo-relative path, even though it ends in ".md".
2312
+ // The comment that stood here claimed ANCHOR_LINK_RE's `.md$` requirement already
2313
+ // excluded http(s) — it does not: `https://host/README.md#install` ends in ".md"
2314
+ // exactly as happily as a local file, so it was joined against the linking file's
2315
+ // directory and reported as missing, at `fail` severity, with a mangled path. The
2316
+ // false comment is why the gap survived review, so it is corrected rather than
2317
+ // merely supplemented (#184). Two shapes, because the second carries no scheme:
2318
+ // an absolute URL (`https:`, `mailto:`) and a protocol-relative one (`//host/…`).
2319
+ // Checked BEFORE the repo-absolute `/` branch below — `//host/x.md` starts with
2320
+ // "/" too, and would otherwise be sliced into the path `/host/x.md`.
2321
+ if (rawTarget && (/^[a-z][a-z0-9+.-]*:/i.test(rawTarget) || rawTarget.startsWith("//"))) continue;
2322
+ const targetPath = rawTarget ? (rawTarget.startsWith("/") ? rawTarget.slice(1) : join(dir, rawTarget)) : file;
2323
+ const normalized = targetPath.split("/").filter((p) => p !== ".").join("/");
2324
+ const slugs = slugsFor(normalized);
2325
+ if (slugs === null) {
2326
+ fail(`${file}:${line}: links to ${normalized}#${fragment}, but ${normalized} does not exist`);
2327
+ continue;
2328
+ }
2329
+ if (!slugs.has(fragment)) {
2330
+ // Ranked by edit distance to the unresolved fragment, ascending, so "nearest"
2331
+ // means what it says (#187 — it used to be the first five headings in document
2332
+ // order, unrelated to the broken fragment). Ties break on document order (the
2333
+ // Set's insertion order) so the message is deterministic — it is asserted in
2334
+ // tests, and a nondeterministic suggestion list would make the suite flaky.
2335
+ const near = [...slugs]
2336
+ .map((slug, index) => ({ slug, index, dist: levenshtein(fragment, slug) }))
2337
+ .sort((a, b) => a.dist - b.dist || a.index - b.index)
2338
+ .slice(0, 5)
2339
+ .map((entry) => entry.slug);
2340
+ fail(
2341
+ `${file}:${line}: anchor #${fragment} does not resolve in ${normalized} — ` +
2342
+ (near.length ? `nearest headings: ${near.join(", ")}` : "that file has no headings at all"),
2343
+ );
2344
+ }
2345
+ }
2346
+ }
2347
+ }
2348
+
2349
+ function checkClaudeMdSize(src, warn) {
2350
+ // #417: measure what is LOADED, not one file. A thin-shell CLAUDE.md (`@AGENTS.md` plus the
2351
+ // by-name tool blocks) is tiny by construction, so measuring it alone would neuter this guard
2352
+ // while a bloated AGENTS.md rides in behind it on every turn. The loaded set is CLAUDE.md plus
2353
+ // every in-repo file it @-imports, recursively (tools/lib/instruction-file.js).
2354
+ const { files } = instructionFile.collectLoaded((p) => src.readFile(p), "CLAUDE.md");
2355
+ if (!files.length) return; // no CLAUDE.md here — a separate concern (project.yml already covers "undescribed")
2356
+
2357
+ let bytes = 0;
2358
+ let authoredBytes = 0;
2359
+ const perFile = [];
2360
+ for (const f of files) {
2361
+ const { authoredLines, malformed } = splitDerivedSpans(f.text); // markers pair within one file
2362
+ for (const problem of malformed) {
2363
+ warn(`${f.path} has a malformed colab:derived marker (${problem}) — treating the affected span as authored, not derived, until it's fixed`);
2364
+ }
2365
+ const fileAuthored = Buffer.byteLength(authoredLines.join("\n"), "utf8");
2366
+ bytes += Buffer.byteLength(f.text, "utf8");
2367
+ authoredBytes += fileAuthored;
2368
+ perFile.push({ path: f.path, authoredLines, authoredBytes: fileAuthored });
2369
+ }
2370
+ const derivedBytes = Math.max(0, bytes - authoredBytes);
2371
+
2372
+ if (authoredBytes > CLAUDE_MD_MAX_BYTES) {
2373
+ const totalNote = derivedBytes > 0
2374
+ ? ` (of ${bytes} bytes total; ${derivedBytes} bytes are marked colab:derived and excluded — #117)`
2375
+ : "";
2376
+ const subject = files.length === 1
2377
+ ? "CLAUDE.md is"
2378
+ : `CLAUDE.md plus its @-imports (${files.slice(1).map((f) => f.path).join(", ")}) is`;
2379
+ warn(
2380
+ `${subject} ${authoredBytes} bytes (~${(authoredBytes / 1024).toFixed(1)} KB)${totalNote} — over the ` +
2381
+ `${CLAUDE_MD_MAX_BYTES / 1024} KB advisory ceiling (#64). It is loaded in full into every session before ` +
2382
+ `any work starts; if the knowledge belongs in docs/, the ${files.length === 1 ? "CLAUDE.md" : "instruction-file"} change is a pointer, not a copy (code-wrap A2)`,
2383
+ );
2384
+ }
2385
+
2386
+ // Median over non-empty PHYSICAL lines, derived spans excluded — a monster line is one
2387
+ // that never wrapped, so a line-count-based reader (like A2's own cited metric) never
2388
+ // sees it either. Excluding derived lines here too: a generated block can legitimately
2389
+ // contain a long row, and that is not the "pointer became a copy" signature this hunts.
2390
+ // Per FILE (#417): each file against its own median, so a fat imported file is blamed by name.
2391
+ for (const f of perFile) {
2392
+ const lens = f.authoredLines.filter((l) => l.length > 0).map((l) => Buffer.byteLength(l, "utf8")).sort((a, b) => a - b);
2393
+ if (lens.length < 2) continue; // no meaningful median from 0 or 1 lines
2394
+ const median = lens[Math.floor(lens.length / 2)];
2395
+ const worst = lens[lens.length - 1];
2396
+ if (median > 0 && worst > CLAUDE_MD_LINE_ABS_FLOOR && worst > median * CLAUDE_MD_LINE_MULTIPLE) {
2397
+ const pct = ((worst / f.authoredBytes) * 100).toFixed(1);
2398
+ warn(
2399
+ `${f.path} has a single line of ${worst} bytes — ${(worst / median).toFixed(1)}x the file's median line ` +
2400
+ `(${median} bytes), ${pct}% of authored content (#64). That is the "pointer became a copy" signature: a ` +
2401
+ `router line should name where the depth lives, not reproduce it`,
2402
+ );
2403
+ }
2404
+ }
2405
+ }
2406
+
2407
+ // #417: CLAUDE.md as a thin shell over AGENTS.md. Two silent failures that shape invites:
2408
+ //
2409
+ // 1. A tool-generated block (one framework's guidelines generator writes the same ~200-line
2410
+ // block into BOTH files) sits in CLAUDE.md and in AGENTS.md. Once CLAUDE.md imports
2411
+ // AGENTS.md that block is loaded twice into every session, and the generator re-adds it
2412
+ // after any hand cleanup — the fix is the generator's target config, not an edit.
2413
+ // 2. The handbook's Conventions block is moved into AGENTS.md along with the prose. Its stamp
2414
+ // is then invisible to this audit's drift check, `colab update` and handbook-sync, which all
2415
+ // look for it in CLAUDE.md BY NAME — the repo silently reads as never adopted.
2416
+ //
2417
+ // Both WARN, never FAIL: neither stops anything working, they cost tokens or drift tracking.
2418
+ // Byte-identical CLAUDE.md and AGENTS.md (a symlinked or copied pair) are ONE file here, or
2419
+ // every symlinked repo would warn on a duplicate it does not have.
2420
+ function checkInstructionFileBlocks(src, warn) {
2421
+ const read = (p) => src.readFile(p);
2422
+ const loaded = instructionFile.collectLoaded(read, "CLAUDE.md").files;
2423
+ const claude = loaded.find((f) => f.path === "CLAUDE.md");
2424
+ const scan = loaded.map((f) => ({ path: f.path, text: f.text }));
2425
+ const agents = read("AGENTS.md");
2426
+ if (agents !== null && !scan.some((f) => f.path === "AGENTS.md")) scan.push({ path: "AGENTS.md", text: agents });
2427
+ if (scan.length < 2) return;
2428
+ if (claude && agents !== null && claude.text === agents) return; // one file under two names
2429
+
2430
+ const loadedPaths = new Set(loaded.map((f) => f.path));
2431
+ for (const { id, paths } of instructionFile.duplicateToolBlocks(scan)) {
2432
+ const both = paths.join(" and ");
2433
+ if (paths.every((p) => loadedPaths.has(p))) {
2434
+ warn(
2435
+ `tool block "${id}" appears in both ${both}, and CLAUDE.md imports the other, so it is loaded twice into ` +
2436
+ `every session — configure the generator to write AGENTS.md only, then delete the CLAUDE.md copy (#417)`,
2437
+ );
2438
+ } else {
2439
+ warn(`tool block "${id}" appears in both ${both} — keep one copy, in AGENTS.md, and configure the generator to write only there (#417)`);
2440
+ }
2441
+ }
2442
+
2443
+ const hasBlock = (t) => !!(parseClaudeStamp(t) || looksLikeHandbookClaude(t));
2444
+ if (!(claude && hasBlock(claude.text))) {
2445
+ const elsewhere = scan.filter((f) => f.path !== "CLAUDE.md" && hasBlock(f.text)).map((f) => f.path);
2446
+ if (elsewhere.length) {
2447
+ warn(
2448
+ `the colab-handbook Conventions block is in ${elsewhere.join(", ")}, not CLAUDE.md — the audit, handbook-sync ` +
2449
+ `and \`colab update\` look for it in CLAUDE.md by name, so its stamp is invisible there; move it back into ` +
2450
+ `CLAUDE.md, next to the @AGENTS.md import (#417)`,
2451
+ );
2452
+ }
2453
+ }
2454
+ }
2455
+
2456
+ // #419: the rule #417 documented, reported. CLAUDE.md holds only the `@AGENTS.md` import, blank
2457
+ // lines and recognised tool blocks (the Conventions block, paired `BEGIN:`/`<name>:start` blocks);
2458
+ // every line of repo prose belongs in AGENTS.md. Two findings, each named by a stable token at the
2459
+ // start of its text so a reader can grep for it:
2460
+ //
2461
+ // prose-in-claude-md — CLAUDE.md carries anything else; the line ranges are named. Covers both
2462
+ // the legacy prose-only file and a thin shell with prose added next to the
2463
+ // import.
2464
+ // no-agents-md — the repo has a CLAUDE.md but no AGENTS.md, so its prose has nowhere to go.
2465
+ // A repo with neither file is not this check's business (no instruction
2466
+ // file at all is an adoption gap, reported elsewhere).
2467
+ //
2468
+ // WARN, never FAIL: existing repos migrate over time (handbook-sync's graft step moves the prose).
2469
+ // Byte-identical CLAUDE.md and AGENTS.md (a symlinked or copied pair) are one file here, as in
2470
+ // checkInstructionFileBlocks: there is nothing to move, and the prose is loaded once.
2471
+ function checkInstructionFileShape(src, warn) {
2472
+ const claude = src.readFile("CLAUDE.md");
2473
+ if (claude === null || claude === undefined) return;
2474
+ const agents = src.readFile("AGENTS.md");
2475
+ if (agents === null || agents === undefined) {
2476
+ warn(
2477
+ `no-agents-md: the repo has a CLAUDE.md but no AGENTS.md — repo prose belongs in AGENTS.md, with CLAUDE.md ` +
2478
+ `reduced to \`@AGENTS.md\` plus tool blocks (CONVENTIONS.md §9 step 5; handbook-sync's graft step does the move) (#419)`,
2479
+ );
2480
+ } else if (agents === claude) {
2481
+ return;
2482
+ }
2483
+ const residue = instructionFile.shellResidue(claude);
2484
+ if (!residue.length) return;
2485
+ const shape = instructionFile.isThinShell(claude)
2486
+ ? "next to its @AGENTS.md import"
2487
+ : "and it has no @AGENTS.md import (a legacy prose-only file)";
2488
+ warn(
2489
+ `prose-in-claude-md: CLAUDE.md lines ${instructionFile.lineRanges(residue, claude)} carry repo prose ${shape} — move ` +
2490
+ `them to AGENTS.md and keep CLAUDE.md to the import, blank lines and tool blocks such as the Conventions ` +
2491
+ `block (CONVENTIONS.md §9 step 5; handbook-sync's graft step does the move) (#419)`,
2492
+ );
2493
+ }
2494
+
2495
+ // `deploy: manual` promises that the hand-deploy procedure is written down and findable.
2496
+ // An unwritten runbook is how "only one person can ship this" happens, so the field is
2497
+ // required and the path is verified — but verification degrades by source:
2498
+ //
2499
+ // local working tree → authoritative. A declared path that is not on disk is a FAIL.
2500
+ // remote (gh API) → best-effort. A miss can mean "file absent" OR "the API read
2501
+ // failed" (private repo, token scope, rate limit, default branch
2502
+ // differs). Those are indistinguishable from here, so a miss is an
2503
+ // ADVISORY naming both possibilities. We would rather under-report
2504
+ // than invent a violation — the same reason `branches === null`
2505
+ // downgrades the trunk check to "unverified".
2506
+ // `why` names the deploy shape that OWES the runbook, so the finding reads honestly whether the
2507
+ // caller is `deploy: manual` (a human runs it) or `deploy: tag` deployed OUTSIDE CI (a GitOps
2508
+ // poller runs it). Both share the same invariant: the deploy runs off no in-repo workflow, so the
2509
+ // path to production must be WRITTEN DOWN or nobody but its author can ship it.
2510
+ // ---- a deploy trigger that fires on a pre-release tag (#332) ---------------
2511
+ // The logic lives in tools/lib/workflow-triggers.js (#338) so `colab release cut` refuses on the
2512
+ // same finding; this maps its severity onto the audit's fail/warn.
2513
+ function checkPrereleaseTagTrigger(src, workflows, deploy, fail, warn) {
2514
+ for (const f of prereleaseTagTriggers({ readFile: (p) => src.readFile(p), workflows, deploy })) {
2515
+ (f.level === "fail" ? fail : warn)(f.text);
2516
+ }
2517
+ }
2518
+
2519
+ // ---- the release workflow: colab release cut/finalize --auto (#425) -----------
2520
+ // Recognises any workflow that runs `colab release cut --auto` or `release finalize --auto` —
2521
+ // a copy of templates/release-auto.yml or a hand-written one, by what it RUNS, not by its name.
2522
+ // Three advisories, each a way such a workflow silently does nothing or does too much:
2523
+ // 1. the release rung leaves candidates off here, so every cut is a refusal;
2524
+ // 2. it tags but publishes nothing itself while another workflow waits on the tag push — a tag
2525
+ // pushed with GITHUB_TOKEN never triggers another workflow, so no Release ever appears;
2526
+ // 3. it commits or pushes something other than a tag — the release workflow reads and creates
2527
+ // tags, never commits. The one non-tag push it may make is a promotion, and only through
2528
+ // `colab promote --auto` (#440), whose gate is the descriptor — never a hand-written push.
2529
+ // Warn, never fail: each is a judgement about a file the repo owns.
2530
+ const RELEASE_AUTO_RUN = /\brelease\s+(cut|finalize)\s+--auto\b/;
2531
+ function releaseAutoFindings({ readFile, workflows, cfg }) {
2532
+ const out = [];
2533
+ const effective = cfg ? releasePolicy.evaluateRelease(cfg).effective : null;
2534
+ for (const wf of workflows || []) {
2535
+ const text = readFile(`.github/workflows/${wf}`);
2536
+ if (!text || !RELEASE_AUTO_RUN.test(text)) continue;
2537
+ const runsCut = /\brelease\s+cut\s+--auto\b/.test(text);
2538
+ if (runsCut && effective && effective.candidates === "off") {
2539
+ out.push(`${wf} runs \`colab release cut --auto\`, but the release rung leaves candidates off on this descriptor (${effective.route === null ? "no route" : `route ${effective.route}`}) — every run refuses; remove the workflow, or change exposure/deploy/release: deliberately (CONVENTIONS.md §6)`);
2540
+ }
2541
+ const publishesHere = /\bgh\s+release\s+create\b/.test(text) || /action-gh-release/.test(text) || /uses:\s*\.\/\.github\/workflows\//.test(text);
2542
+ if (!publishesHere) {
2543
+ const waiting = workflows.filter((o) => o !== wf).filter((o) => {
2544
+ const t = readFile(`.github/workflows/${o}`);
2545
+ return t && workflowFiresOnTag(parseWorkflowOn(t), "v1.2.0");
2546
+ });
2547
+ if (waiting.length) {
2548
+ out.push(`${wf} creates release tags but publishes nothing in its own run, while ${waiting.join(", ")} fires on the tag push — a tag pushed with GITHUB_TOKEN triggers no other workflow, so that never runs; publish in the same run (templates/release-auto.yml) or call it via workflow_call`);
2549
+ }
2550
+ }
2551
+ const pushesNonTag = text.split("\n").some((l) => /\bgit\s+push\b/.test(l) && !/--tags|refs\/tags|\$TAG\b|\$\{TAG\}/.test(l));
2552
+ if (/\bgit\s+commit\b/.test(text) || pushesNonTag) {
2553
+ out.push(`${wf} runs \`colab release … --auto\` and also commits or pushes a non-tag ref — the release workflow reads and creates tags, never commits; move that step elsewhere`);
2554
+ }
2555
+ }
2556
+ return out;
2557
+ }
2558
+ function checkReleaseAuto(src, workflows, cfg, warn) {
2559
+ for (const text of releaseAutoFindings({ readFile: (p) => src.readFile(p), workflows, cfg })) warn(text);
2560
+ }
2561
+
2562
+ // ---- a private repo never publishes to public npm (#432) ---------------------
2563
+ // Visibility is read from the GitHub API, and only when the repo has an npm surface at all (so an
2564
+ // npm-free repo costs no API call). Unreadable / no remote → reported as a warn, never passed.
2565
+ //
2566
+ // #442 rides on the same visibility read: a private repo whose workflows upload GitHub Release
2567
+ // assets is installing from somewhere other than npx — advisory (warn), never a failure.
2568
+ function checkPrivateNpm(src, workflows, fail, warn) {
2569
+ const reader = { readFile: (p) => src.readFile(p), listDir: (p) => src.listDir(p), workflows };
2570
+ const npmSurface = npmGuard.exposure(reader).problems.length > 0;
2571
+ const assetSurface = npmGuard.releaseAssetUploads(workflows, reader.readFile).length > 0;
2572
+ if (!npmSurface && !assetSurface) return;
2573
+ const meta = src.metadata ? src.metadata() : { status: "unreadable" };
2574
+ let visibility = null;
2575
+ if (meta.status === "ok" && meta.data) {
2576
+ visibility = meta.data.visibility || (meta.data.private === true ? "private" : meta.data.private === false ? "public" : null);
2577
+ }
2578
+ const all = [
2579
+ ...(npmSurface ? npmGuard.findings({ ...reader, visibility }) : []),
2580
+ ...(assetSurface ? npmGuard.assetFindings({ ...reader, visibility }) : []),
2581
+ ];
2582
+ for (const f of all) (f.level === "fail" ? fail : warn)(f.text);
2583
+ }
2584
+
2585
+ function checkRunbook(src, runbook, fail, warn, why = "deploy: manual") {
2586
+ if (runbook === null || runbook === "") {
2587
+ fail(`${why} requires runbook: — name the committed doc that describes how production is reached (e.g. docs/deploy.md), or nobody but you can ship`);
2588
+ return;
2589
+ }
2590
+ const path = String(runbook).trim().replace(/^\.\//, "");
2591
+ if (src.readFile(path) !== null) return;
2592
+ if (src.kind === "local") fail(`runbook "${runbook}" does not exist in the repo — ${why} points at a doc that is not there`);
2593
+ else warn(`runbook "${runbook}" not found via the API — either it is missing, or the read failed (permissions/branch); verify in a checkout`);
2594
+ }
2595
+
2596
+ // The bug this catches (found in the wild in three of our Tier A repos): a repo moved
2597
+ // its trunk (main -> dev) but its CI workflows' push triggers still named the OLD
2598
+ // branches, so every merge to the real trunk ran ZERO CI — silently — while the B1
2599
+ // gate ("check trunk CI is green") checked runs that could never exist.
2600
+ //
2601
+ // Deploy/release workflows are NOT CI gates: a deploy-*.yml firing on a push to main is a
2602
+ // deploy trigger, not a check, so it must never be counted as "the trunk is gated". We
2603
+ // exclude them by filename (deploy*/release*) and by trigger shape (a tags-only or
2604
+ // workflow_dispatch-only workflow does no branch gating and is not CI-type). This exclusion
2605
+ // is about what COUNTS AS CI here and says nothing about whether the setup is desirable —
2606
+ // a `deploy: push-main` repo is separately a tier A finding above.
2607
+ function checkTrunkCiGated(src, trunk, workflows, branches, fail, warn, { integration = [], exempt = INTEGRATION_BRANCHES } = {}) {
2608
+ if (!trunk || !workflows.length) return;
2609
+
2610
+ const ci = []; // CI-type workflows: { wf, pushGate, prGate, refs }
2611
+ for (const wf of workflows) {
2612
+ if (/^(deploy|release)[-.]/.test(wf)) continue; // deploy/release by filename
2613
+ const on = parseWorkflowOn(src.readFile(`.github/workflows/${wf}`));
2614
+ if (!on.found) continue;
2615
+
2616
+ // Effective push branch gate: an array of patterns | "all" | {ignore:[…]} | null.
2617
+ // Bare `push:` = every branch ("all"); `push:` with only tags = no branch push.
2618
+ let pushGate = null;
2619
+ if (on.events.has("push")) {
2620
+ if (on.pushBranches !== null) pushGate = on.pushBranches;
2621
+ else if (on.pushBranchesIgnore !== null) pushGate = { ignore: on.pushBranchesIgnore };
2622
+ else if (on.pushTags !== null) pushGate = null; // tags-only push
2623
+ else pushGate = "all";
2624
+ }
2625
+ const prGate = (on.events.has("pull_request") || on.events.has("pull_request_target"))
2626
+ ? (on.prBranches !== null ? on.prBranches : "all")
2627
+ : null;
2628
+
2629
+ // Not CI-type if it does no branch-based triggering (tags-only + dispatch, etc.).
2630
+ if (pushGate === null && prGate === null) continue;
2631
+
2632
+ // Positive branch references, for the stale-reference advisory (ignore lists and
2633
+ // glob patterns are not concrete "references" to a branch).
2634
+ const refs = [];
2635
+ for (const list of [on.pushBranches, on.prBranches]) {
2636
+ if (Array.isArray(list)) for (const b of list) if (b) refs.push(b);
2637
+ }
2638
+ ci.push({ wf, pushGate, prGate, refs });
2639
+ }
2640
+
2641
+ // No CI at all here is a DIFFERENT concern (does this repo want CI?) — out of scope.
2642
+ // This check only catches CI that exists but points at the wrong branch.
2643
+ if (!ci.length) return;
2644
+
2645
+ const pushGates = (g, branch) => {
2646
+ if (g === "all") return true;
2647
+ if (Array.isArray(g)) return g.some((p) => globMatch(p, branch));
2648
+ if (g && g.ignore) return !g.ignore.some((p) => globMatch(p, branch));
2649
+ return false;
2650
+ };
2651
+ const gatedBySomeWorkflow = (branch) => ci.some((c) => pushGates(c.pushGate, branch));
2652
+
2653
+ if (!gatedBySomeWorkflow(trunk)) {
2654
+ const gates = ci.map((c) => {
2655
+ if (Array.isArray(c.pushGate)) return `${c.wf} gates: ${c.pushGate.join(", ")}`;
2656
+ if (c.pushGate === "all") return `${c.wf} gates: all branches`;
2657
+ return `${c.wf}: pull_request only`;
2658
+ });
2659
+ fail(`trunk "${trunk}" is not CI-gated — no workflow triggers on push to it (${gates.join("; ")})`);
2660
+ }
2661
+
2662
+ // A declared integration line without its own push gate is an ADVISORY, never a failure. Work
2663
+ // merges into such a line the same way it merges into trunk, so ungated is a real gap — but a
2664
+ // line that is not yet CI-gated is a normal early state, and failing the repo for it would push
2665
+ // teams to declare the line nowhere (which is the state this field exists to end). Trunk's gate
2666
+ // is the one that must exist, because trunk is what reaches a release.
2667
+ for (const b of integration) {
2668
+ if (!gatedBySomeWorkflow(b)) {
2669
+ warn(`integration line "${b}" is not CI-gated — no workflow triggers on push to it, so merges into it run zero CI (advisory: an ungated line is a normal early state)`);
2670
+ }
2671
+ }
2672
+
2673
+ // Stale-reference advisory: a workflow names a branch that does not exist. Standard
2674
+ // integration aliases (main/master/dev/trunk) and this repo's declared integration
2675
+ // lines are exempt — teams list them defensively; the anti-pattern is a
2676
+ // project-specific ghost like develop/workos.
2677
+ if (Array.isArray(branches)) {
2678
+ for (const c of ci) {
2679
+ const ghosts = [...new Set(c.refs)]
2680
+ .filter((b) => !/[*?[]/.test(b)) // glob patterns aren't concrete branches
2681
+ .filter((b) => !exempt.has(b))
2682
+ .filter((b) => !branches.includes(b));
2683
+ if (ghosts.length) warn(`${c.wf} triggers on nonexistent branch(es): ${ghosts.join(", ")}`);
2684
+ }
2685
+ }
2686
+ }
2687
+
2688
+ function collectToolchain(src, cfg, workflows) {
2689
+ const findings = [];
2690
+
2691
+ // --- declared -------------------------------------------------------------
2692
+ const declared = {
2693
+ node: cfg && "node" in cfg ? cfg.node : null,
2694
+ php: cfg && "php" in cfg ? cfg.php : null,
2695
+ python: cfg && "python" in cfg ? cfg.python : null,
2696
+ };
2697
+
2698
+ // --- manifest -------------------------------------------------------------
2699
+ const manifest = {
2700
+ node: null, nodeRaw: null, nodeFrom: null,
2701
+ php: null, phpRaw: null, phpFrom: null,
2702
+ python: null, pythonRaw: null, pythonFrom: null,
2703
+ };
2704
+
2705
+ const nvmrc = src.readFile(".nvmrc");
2706
+ if (nvmrc && nvmrc.trim()) {
2707
+ manifest.nodeRaw = nvmrc.split("\n").find((l) => l.trim() && !l.trim().startsWith("#"))?.trim() ?? null;
2708
+ manifest.node = normaliseVersion(manifest.nodeRaw);
2709
+ manifest.nodeFrom = ".nvmrc";
2710
+ }
2711
+ const pkgRaw = src.readFile("package.json");
2712
+ let pkg = null;
2713
+ if (pkgRaw) {
2714
+ try {
2715
+ pkg = JSON.parse(pkgRaw);
2716
+ } catch (e) {
2717
+ findings.push({ level: "fail", text: `package.json does not parse: ${e.message.split("\n")[0]}` });
2718
+ }
2719
+ }
2720
+ if (pkg && !manifest.node && pkg.engines?.node) {
2721
+ manifest.nodeRaw = pkg.engines.node;
2722
+ manifest.node = normaliseVersion(pkg.engines.node);
2723
+ manifest.nodeFrom = "engines.node";
2724
+ }
2725
+
2726
+ const composerRaw = src.readFile("composer.json");
2727
+ let composer = null;
2728
+ if (composerRaw) {
2729
+ try {
2730
+ composer = JSON.parse(composerRaw);
2731
+ } catch (e) {
2732
+ findings.push({ level: "fail", text: `composer.json does not parse: ${e.message.split("\n")[0]}` });
2733
+ }
2734
+ }
2735
+ if (composer?.require?.php) {
2736
+ manifest.phpRaw = composer.require.php;
2737
+ manifest.php = normaliseVersion(composer.require.php);
2738
+ manifest.phpFrom = "composer.json require.php";
2739
+ }
2740
+
2741
+ // Python. Precedence mirrors node's: the dedicated version file first (pyenv's
2742
+ // .python-version, which local tooling also reads), then the package manifest.
2743
+ //
2744
+ // requirements.txt is deliberately ABSENT from this list — it pins dependencies,
2745
+ // never the interpreter. A repo carrying only a requirements.txt has declared
2746
+ // nothing about which Python it runs on, and the undeclared-but-pinned advisory
2747
+ // below is exactly the right thing to say about it.
2748
+ const pyver = src.readFile(".python-version");
2749
+ if (pyver && pyver.trim()) {
2750
+ manifest.pythonRaw = pyver.split("\n").find((l) => l.trim() && !l.trim().startsWith("#"))?.trim() ?? null;
2751
+ manifest.python = normaliseVersion(manifest.pythonRaw);
2752
+ manifest.pythonFrom = ".python-version";
2753
+ }
2754
+ const pyproject = src.readFile("pyproject.toml");
2755
+ if (pyproject && !manifest.python) {
2756
+ // A line match, not a TOML parser: this tool is dependency-free by design, and
2757
+ // requires-python is a single top-level string in [project].
2758
+ const m = pyproject.match(/^\s*requires-python\s*=\s*["']([^"']+)["']/m);
2759
+ if (m) {
2760
+ manifest.pythonRaw = m[1];
2761
+ manifest.python = normaliseVersion(m[1]);
2762
+ manifest.pythonFrom = "pyproject.toml requires-python";
2763
+ }
2764
+ }
2765
+
2766
+ // --- what the workflows actually pin -------------------------------------
2767
+ const pins = { node: [], php: [], python: [] };
2768
+ for (const wf of workflows) {
2769
+ const text = src.readFile(`.github/workflows/${wf}`);
2770
+ if (!text) continue;
2771
+ for (const [, v] of text.matchAll(/^\s*node-version:\s*["']?([^"'\s#]+)/gm)) {
2772
+ if (!v.includes("${{")) pins.node.push({ wf, v: normaliseVersion(v) });
2773
+ }
2774
+ for (const [, v] of text.matchAll(/^\s*php-version:\s*["']?([^"'\s#]+)/gm)) {
2775
+ if (!v.includes("${{")) pins.php.push({ wf, v: normaliseVersion(v) });
2776
+ }
2777
+ for (const [, v] of text.matchAll(/^\s*python-version:\s*["']?([^"'\s#]+)/gm)) {
2778
+ if (!v.includes("${{")) pins.python.push({ wf, v: normaliseVersion(v) });
2779
+ }
2780
+ }
2781
+
2782
+ for (const eco of ["node", "php", "python"]) {
2783
+ const d = declared[eco] ? normaliseVersion(declared[eco]) : null;
2784
+ const m = manifest[eco];
2785
+ const rawConstraint = manifest[`${eco}Raw`];
2786
+ const from = manifest[`${eco}From`];
2787
+
2788
+ // Descriptor vs manifest. If the manifest states a range, the descriptor's
2789
+ // concrete version must live inside it; otherwise compare them directly.
2790
+ if (d && m) {
2791
+ const agrees = isRange(rawConstraint) ? satisfiesConstraint(d, rawConstraint) : prefixAgree(d, m);
2792
+ if (!agrees) {
2793
+ findings.push({ level: "fail", text: `${eco}: project.yml=${d} but ${from}=${rawConstraint}` });
2794
+ }
2795
+ }
2796
+
2797
+ // Declared truth vs what the workflows actually pin. project.yml wins as the
2798
+ // reference when present; otherwise the manifest is the reference.
2799
+ const truthLabel = d ? "project.yml" : from;
2800
+ const reference = d || m;
2801
+ const referenceIsRange = !d && isRange(rawConstraint);
2802
+ for (const p of pins[eco]) {
2803
+ if (!p.v || !reference) continue;
2804
+ const agrees = referenceIsRange ? satisfiesConstraint(p.v, rawConstraint) : prefixAgree(reference, p.v);
2805
+ if (!agrees) {
2806
+ const shown = referenceIsRange ? rawConstraint : normaliseVersion(reference);
2807
+ findings.push({ level: "fail", text: `${eco}: ${truthLabel}=${shown} but ${p.wf} pins ${p.v}` });
2808
+ }
2809
+ }
2810
+
2811
+ // workflows disagreeing with EACH OTHER is the exact bug that started this:
2812
+ // ci.yml on Node 20, deploy-xserver.yml on Node 22.
2813
+ const pinned = pins[eco].filter((p) => p.v);
2814
+ const inconsistent = pinned.some((p) => !prefixAgree(p.v, pinned[0].v));
2815
+ if (inconsistent) {
2816
+ findings.push({
2817
+ level: "fail",
2818
+ text: `${eco}: workflows disagree — ${pins[eco].map((p) => `${p.wf}=${p.v}`).join(", ")}`,
2819
+ });
2820
+ }
2821
+
2822
+ // Nothing declared anywhere, but CI pins something: the pin is the only source
2823
+ // of truth and nobody can see it without opening the YAML.
2824
+ if (!reference && pins[eco].length) {
2825
+ findings.push({
2826
+ level: "warn",
2827
+ text: `${eco}: undeclared — only pinned inside ${[...new Set(pins[eco].map((p) => p.wf))].join(", ")} (declare it in project.yml)`,
2828
+ });
2829
+ }
2830
+ }
2831
+
2832
+ return { findings };
2833
+ }
2834
+
2835
+ // -------------------------------------------------------------------- config load
2836
+
2837
+ function loadTargets(opts) {
2838
+ const targets = [];
2839
+
2840
+ for (const p of opts.locals) {
2841
+ targets.push({ kind: "local", path: p, label: labelForPath(p) });
2842
+ }
2843
+
2844
+ const entries = [];
2845
+ if (opts.slugs.length) {
2846
+ entries.push(...opts.slugs);
2847
+ } else if (!opts.locals.length) {
2848
+ const cfg = resolveConfig(opts);
2849
+ opts.resolvedConfig = cfg; // surfaced in the report header
2850
+ for (const line of readFileSync(cfg.path, "utf8").split(/\r?\n/)) {
2851
+ const s = line.replace(/#.*$/, "").trim();
2852
+ if (s) entries.push(s);
2853
+ }
2854
+ }
2855
+
2856
+ for (const e of entries) {
2857
+ // A path if it looks like one or exists on disk; otherwise an owner/name slug.
2858
+ const looksPath = e.startsWith("/") || e.startsWith("~") || e.startsWith(".");
2859
+ const expanded = e.startsWith("~") ? join(process.env.HOME || "", e.slice(1)) : e;
2860
+ if (looksPath || existsSync(expanded)) {
2861
+ targets.push({ kind: "local", path: expanded, label: labelForPath(expanded) });
2862
+ } else if (/^[^/]+\/[^/]+$/.test(e)) {
2863
+ targets.push({ kind: "remote", slug: e, label: e });
2864
+ } else {
2865
+ targets.push({ kind: "local", path: expanded, label: e }); // will report "does not exist"
2866
+ }
2867
+ }
2868
+ return targets;
2869
+ }
2870
+
2871
+ // Two path segments read better than one in a report: `company/project`.
2872
+ function labelForPath(p) {
2873
+ const r = resolve(p.startsWith("~") ? join(process.env.HOME || "", p.slice(1)) : p);
2874
+ const parent = basename(dirname(r));
2875
+ return parent && parent !== "/" ? `${parent}/${basename(r)}` : basename(r);
2876
+ }
2877
+
2878
+ // ------------------------------------------------------------------------- output
2879
+
2880
+ function report(results, opts, ctx) {
2881
+ if (opts.json) {
2882
+ console.log(JSON.stringify({
2883
+ generated: new Date().toISOString(),
2884
+ handbook: { version: ctx.handbook.version, untagged: ctx.handbook.untagged, root: ctx.handbook.root },
2885
+ configSource: opts.resolvedConfig?.source ?? (opts.locals.length || opts.slugs.length ? "ad-hoc (--local / positional)" : null),
2886
+ // Whether the metadata identity scan ran, stated on every run — a consumer must never
2887
+ // have to infer it from the absence of findings. The terms themselves are NEVER here.
2888
+ identity: ctx.identity
2889
+ ? { scanned: true, vocabulary: ctx.identity.path, source: ctx.identity.source, terms: ctx.identity.count }
2890
+ : { scanned: false, reason: "not requested (--identity)" },
2891
+ results,
2892
+ }, null, 2));
2893
+ return;
2894
+ }
2895
+
2896
+ // Header: which repo list + handbook version, so a scheduled run is self-documenting.
2897
+ if (opts.resolvedConfig) console.log(`repo list: ${opts.resolvedConfig.source}`);
2898
+ console.log(`handbook: ${ctx.handbook.version}${ctx.handbook.untagged ? " (untagged — stamp checks inactive)" : ""}`);
2899
+ // Whether repository METADATA was scanned, said out loud on every run. A per-repo advisory
2900
+ // would be the alternative, and on a fleet where most repos have no vocabulary configured
2901
+ // it would mark every one of them non-clean — training the reader to ignore the report,
2902
+ // which is a worse failure than the silence it fixes. Once per run, always, is the honest
2903
+ // middle: no run can be mistaken for having checked something it did not.
2904
+ console.log(ctx.identity
2905
+ ? `identity: ${ctx.identity.count} term(s) from ${ctx.identity.path} (${ctx.identity.source}) — public repository metadata scanned`
2906
+ : "identity: repository metadata NOT scanned (pass --identity)");
2907
+ console.log("");
2908
+
2909
+ const shown = opts.quiet ? results.filter((r) => !r.clean) : results;
2910
+ const width = Math.max(0, ...shown.map((r) => r.repo.length));
2911
+ const tierW = 6;
2912
+
2913
+ for (const r of shown) {
2914
+ const tier = r.tier ? `tier ${r.tier}` : "tier ?";
2915
+ const head = `${r.repo.padEnd(width)} ${tier.padEnd(tierW)}`;
2916
+ const cont = "".padEnd(width + 2 + tierW + 2); // continuation indent
2917
+
2918
+ const lines = [];
2919
+ // The handbook's own row says WHY it carries no stamp findings. Without this it
2920
+ // would read as clean-by-luck, which is indistinguishable from a check that
2921
+ // quietly stopped working.
2922
+ if (r.self) lines.push("⌂ handbook source — every rule applies except its own stamps (it has nothing to copy from)");
2923
+ else if (r.adoption === "local") lines.push(`⌂ adopted locally, not committed — descriptor hidden by .git/info/exclude; a repo the fleet does not own (CONVENTIONS.md §9)${r.clean ? " ✓" : ""}`);
2924
+ else if (r.clean) lines.push("✓");
2925
+ r.findings.forEach((f) => lines.push(`${f.level === "fail" ? "⚠" : "·"} ${f.text}`));
2926
+
2927
+ // Repeat the name on every line so the output stays greppable.
2928
+ lines.forEach((l, i) => console.log(`${i === 0 ? head : cont} ${l}`));
2929
+ }
2930
+
2931
+ const failed = results.filter((r) => !r.ok).length;
2932
+ const warned = results.filter((r) => r.ok && !r.clean).length;
2933
+ console.log("");
2934
+ console.log(`${results.length} repo(s): ${results.length - failed - warned} clean, ${warned} with advisories, ${failed} with problems.`);
2935
+ }
2936
+
2937
+ /**
2938
+ * Resolve + load the identity vocabulary for a --identity run, or exit 2.
2939
+ *
2940
+ * EVERY failure here is a usage error, never a degraded run: the operator asked for a scan
2941
+ * that has one input, and there is no honest way to perform it without that input. A missing
2942
+ * file, an unreadable one and a malformed one all end the run before a single repo is audited
2943
+ * — because the alternative is a sweep that prints "N clean" over a check that never ran,
2944
+ * which is the exact outcome this part of #228 exists to make impossible.
2945
+ *
2946
+ * `git config colab.identityVocabulary` is deliberately NOT consulted: it is a per-repo
2947
+ * setting and this tool sweeps many repos at once, so there is no single repo whose config
2948
+ * could answer for the run. The hook (which has exactly one repo) does read it.
2949
+ */
2950
+ function loadIdentityVocabulary() {
2951
+ const resolved = identity.resolveVocabularyPath({ env: process.env });
2952
+ const loaded = identity.loadVocabulary(resolved.path);
2953
+ if (!loaded) {
2954
+ die(`--identity: no vocabulary at ${resolved.path} (${resolved.source}).\n`
2955
+ + " It is supplied by path and kept outside every repo — start from the handbook's\n"
2956
+ + " templates/identity-vocabulary.example, or set COLAB_IDENTITY_VOCAB.");
2957
+ }
2958
+ if (loaded.problems.length) {
2959
+ die(`--identity: the vocabulary at ${resolved.path} is unusable:\n`
2960
+ + loaded.problems.map((p) => ` ${p.message}`).join("\n"));
2961
+ }
2962
+ if (!loaded.terms.length) {
2963
+ die(`--identity: the vocabulary at ${resolved.path} has no terms — an empty list is not a scan.`);
2964
+ }
2965
+ return { path: resolved.path, source: resolved.source, terms: loaded.terms, count: loaded.terms.length };
2966
+ }
2967
+
2968
+ // The usage block is this file's own leading comment, rendered on demand.
2969
+ function helpText() {
2970
+ return readFileSync(fileURLToPath(import.meta.url), "utf8")
2971
+ .split("\n")
2972
+ .filter((l) => l.startsWith("//"))
2973
+ .map((l) => l.replace(/^\/\/ ?/, ""))
2974
+ .join("\n");
2975
+ }
2976
+
2977
+ // Returns the exit code rather than taking it — see the note in main.
2978
+ function runAudit(opts) {
2979
+ const targets = loadTargets(opts);
2980
+ if (!targets.length) die("nothing to audit — add entries to the repo list or pass --local <path>");
2981
+
2982
+ const ctx = { handbook: handbookInfo(HANDBOOK_ROOT), templateNames: templateNames(HANDBOOK_ROOT) };
2983
+ ctx.identity = opts.identity ? loadIdentityVocabulary() : null;
2984
+
2985
+ const results = [];
2986
+ for (const t of targets) {
2987
+ try {
2988
+ results.push(auditRepo(t, ctx));
2989
+ } catch (err) {
2990
+ // Degrade gracefully: one broken repo must never take the whole sweep down.
2991
+ results.push({
2992
+ repo: t.label,
2993
+ kind: t.kind,
2994
+ tier: null,
2995
+ ok: false,
2996
+ clean: false,
2997
+ findings: [{ level: "fail", text: `audit crashed: ${err.message.split("\n")[0]}` }],
2998
+ });
2999
+ }
3000
+ }
3001
+
3002
+ report(results, opts, ctx);
3003
+ return results.every((r) => r.ok) ? 0 : 1;
3004
+ }
3005
+
3006
+ // --------------------------------------------------------------------------- main
3007
+
3008
+ /*
3009
+ * Both branches below SET process.exitCode and let Node exit on its own once stdout
3010
+ * has drained. process.exit() would not wait: writes to a pipe are asynchronous, so
3011
+ * exiting straight after console.log() discards whatever is still buffered, handing
3012
+ * the reader a truncated payload *with a success-looking exit code*. Nothing in the
3013
+ * contract signals the failure, so a consumer parses garbage or silently sees less.
3014
+ *
3015
+ * Two things made this expensive to diagnose, both worth remembering:
3016
+ * - `| wc -c` does NOT reproduce it. A shell consumer drains greedily and wins the
3017
+ * race, reporting the full byte count. Only a reader that buffers stdout
3018
+ * (execFile/spawn — i.e. every tool that consumes --json) sees the cut.
3019
+ * - The threshold is the platform's pipe buffer: ~8 KB on macOS, 64 KB on Linux.
3020
+ * So it surfaces per-machine, and only once the report grows past it. Findings
3021
+ * inflate the payload faster than repo count does.
3022
+ *
3023
+ * The exit-code contract is unchanged: 0 clean, 1 findings, 2 usage error.
3024
+ * (Block-comment syntax deliberately: helpText scrapes line comments, and this note
3025
+ * is for maintainers, not users.)
3026
+ */
3027
+
3028
+ const opts = parseArgs(process.argv.slice(2));
3029
+
3030
+ if (opts.help) {
3031
+ console.log(helpText());
3032
+ process.exitCode = 0;
3033
+ } else {
3034
+ process.exitCode = runAudit(opts);
3035
+ }