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

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 +13785 -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 +481 -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,195 @@
1
+ 'use strict';
2
+ /**
3
+ * Claim-record IDENTITY shape — the single decision #264 and #267 both need, so the writer
4
+ * (`cmdClaim`, tools/colab) and the two readers (`tieBreakVerdict` in claim-comments.js,
5
+ * `ghClaimConflicts` in tools/colab) apply ONE rule instead of two independently-evolving ones. Full design in
6
+ * `.claude/plans/issue-264.md` (issues #264, #267); this module holds only the decidable, pure
7
+ * parts — the same split every other tools/lib/*.js module keeps from its tools/colab caller
8
+ * (records.js, place.js, solo.js, blocked-by.js, …).
9
+ *
10
+ * TWO FIELD CLASSES on a claim record:
11
+ * - IDENTITY — login, host, session: who holds it. Compared by the readers. A re-claim may
12
+ * REPLACE these (a real new holder truthfully overwrites), but a blank incoming value never
13
+ * BLANKS a known one recorded by the SAME holder.
14
+ * - PAYLOAD — branch, sessionName: cached convenience, never compared. `branch` is additionally
15
+ * MONOTONIC — a blank incoming value never overwrites a known one from the same holder either,
16
+ * because "no branch recorded" and "branch known but omitted this call" must not collapse to
17
+ * the same `-` on the wire (#264).
18
+ * - `worktree` is in NEITHER class — it is never inherited across a merge. Its absence is the
19
+ * meaningful trunk-checkout shape (#133/#136/#237); silently carrying a previous worktree name
20
+ * forward would misrepresent an intentional trunk-checkout claim as still attached to one.
21
+ *
22
+ * IDENTITY GRANULARITY (#267): `liveClaimComments`/`tieBreakVerdict` used to build identity from
23
+ * only `login@host`, hardcoded — so two sessions of one account on one host are indistinguishable,
24
+ * and the tie-break's own "never yield to ourselves" clause then treats a co-tenant's live claim as
25
+ * our own. `components()` reads a configurable, whitelisted set instead: `login,host` (default,
26
+ * unchanged behaviour) or `login,host,session` (opt-in, distinguishes co-tenants). Kept a KNOB
27
+ * rather than made default, because a session id that is not stable across a restart/resume turns
28
+ * that session's OWN earlier claim comment into a "different" claimant, which then yields to
29
+ * itself — a property of session-management deployment, not of this tool.
30
+ *
31
+ * DEGRADE-ON-MISSING is what makes the fine setting safe to turn on at all: `sameClaimant` compares
32
+ * `session` only when BOTH sides carry a non-empty one. Without this, turning the knob on would
33
+ * make every legacy/session-less claim comment from our own login@host read as a stranger, and any
34
+ * such comment still live (never released) would instantly win every future race.
35
+ */
36
+
37
+ const machine = require('./machine');
38
+
39
+ const DEFAULT_COMPONENTS = Object.freeze(['login', 'host']);
40
+ const FINE_COMPONENTS = Object.freeze(['login', 'host', 'session']);
41
+
42
+ const IDENTITY_SETS = {
43
+ 'login,host': DEFAULT_COMPONENTS,
44
+ 'login,host,session': FINE_COMPONENTS,
45
+ };
46
+
47
+ /**
48
+ * Validation for `colab config set claimIdentity <value>` — refuse a typo before it is ever
49
+ * written, rather than silently degrading later at read time. `""` is valid (unsets → default,
50
+ * same "absent, not falsy" discipline as `notifyUrl`/`journal`).
51
+ */
52
+ function claimIdentityProblem(value) {
53
+ if (value === '' || value === undefined || value === null) return null;
54
+ if (Object.prototype.hasOwnProperty.call(IDENTITY_SETS, value)) return null;
55
+ return `claimIdentity must be "login,host" or "login,host,session" (or "" to unset), got ${JSON.stringify(value)}`;
56
+ }
57
+
58
+ /**
59
+ * The active identity components for THIS invocation. Absent config, or any value that somehow
60
+ * reached disk invalid (a hand-edited config.json, an older/newer colab's different valid set)
61
+ * both degrade quietly to the coarse default — a bad config file must never brick `claim`. A
62
+ * caller that wants to WARN about an invalid-on-disk value runs `claimIdentityProblem` itself on
63
+ * the raw `cfg.claimIdentity`; this function never throws and never logs, matching every other
64
+ * pure function in tools/lib.
65
+ */
66
+ function components(cfg) {
67
+ const raw = cfg && typeof cfg.claimIdentity === 'string' ? cfg.claimIdentity.trim() : '';
68
+ if (!raw) return DEFAULT_COMPONENTS;
69
+ return IDENTITY_SETS[raw] || DEFAULT_COMPONENTS;
70
+ }
71
+
72
+ /**
73
+ * Human-legible identity string for messages and the `identity` field `tieBreakVerdict` sorts
74
+ * exact-timestamp ties on. Coarse: `login@host`. Fine WITH a session on this entry:
75
+ * `login@host#session`. Fine but this entry itself carries no session (a legacy comment): same as
76
+ * coarse — there is nothing finer to show, and inventing a trailing `#` would misrepresent a
77
+ * comment that never had one.
78
+ */
79
+ function identityString(entry, comps) {
80
+ const login = (entry && entry.login) || '';
81
+ const host = (entry && entry.host) || '';
82
+ const session = (entry && entry.session) || '';
83
+ const base = `${login}@${host}`;
84
+ if (comps && comps.includes('session') && session) return `${base}#${session}`;
85
+ return base;
86
+ }
87
+
88
+ /**
89
+ * Is `s` a PLANNER INTENT id rather than a session (#326)? A planner running on every machine
90
+ * claims an issue BEFORE it spawns the session that will do the work, with `--session
91
+ * intent:<id>`; the spawned session's own claim later replaces that value with its real one. An
92
+ * intent id therefore never identifies a session, and must never be compared as one.
93
+ */
94
+ function isIntentSession(s) {
95
+ return /^intent:\S/.test(String(s == null ? '' : s).trim());
96
+ }
97
+
98
+ /**
99
+ * Are `a` and `b` on the SAME machine (#327)? Both carry a `machine` → compare those (a raw id or
100
+ * the `m:` digest a claim comment carries — `machineToken` makes the two comparable); raw ids of
101
+ * DIFFERENT schemes (one machine resolving `iokit:` in one process and the MAC fallback in another)
102
+ * cannot be compared, so they fall through, exactly as `machine.js` `sameMachineWith` does.
103
+ * Otherwise → `canonHost`, so `devbox.local`, `Devbox.` and `devbox.lan` read as one machine: raw
104
+ * `os.hostname()` spells one machine two ways, and a string compare used to split it into two
105
+ * claimants. Blank on both sides compares equal, matching the pre-#327 `'' === ''`.
106
+ */
107
+ function sameHost(a, b) {
108
+ const am = String((a && a.machine) || '').trim();
109
+ const bm = String((b && b.machine) || '').trim();
110
+ if (am && bm) {
111
+ const digested = /^m:/.test(am) || /^m:/.test(bm);
112
+ if (digested) return machine.machineToken(am) === machine.machineToken(bm);
113
+ if (machineScheme(am) === machineScheme(bm)) return am === bm;
114
+ }
115
+ // #369: a host field may be an `h:` token (a comment on a public destination) — sameHostName
116
+ // compares tokens then, and canonHost exactly as before otherwise.
117
+ return machine.sameHostName(a && a.host, b && b.host);
118
+ }
119
+
120
+ function machineScheme(id) {
121
+ const i = id.indexOf(':');
122
+ return i === -1 ? '' : id.slice(0, i);
123
+ }
124
+
125
+ /**
126
+ * Are `a` and `b` the SAME claimant under `comps`? `login` and the machine (`sameHost`, #327) are
127
+ * always required to match — they are the baseline every component set includes. `session`
128
+ * sharpens the match ONLY when `comps` includes it AND both sides carry a non-empty value that is a
129
+ * real session; either side blank, or either side a planner intent id (#326 — replaced by the real
130
+ * session at spawn, so it is not a different claimant), degrades that pair back to the coarse
131
+ * comparison (see the module doc's DEGRADE-ON-MISSING note).
132
+ */
133
+ function sameClaimant(a, b, comps) {
134
+ if (!a || !b) return false;
135
+ if ((a.login || '') !== (b.login || '')) return false;
136
+ if (!sameHost(a, b)) return false;
137
+ if (comps && comps.includes('session') && a.session && b.session
138
+ && !isIntentSession(a.session) && !isIntentSession(b.session)) {
139
+ return a.session === b.session;
140
+ }
141
+ return true;
142
+ }
143
+
144
+ /**
145
+ * The #264 merge rule for writing a claim record. `existing` is the record already on disk (or
146
+ * null on a first claim); `incoming` is what THIS invocation computed (may carry a blank
147
+ * branch/session/sessionName when the caller simply does not have them in hand — e.g. `colab claim
148
+ * N --worktree w` run before a branch is cut). `sameHolder` is true when `incoming` is a
149
+ * reclaim/correction from the SAME holder as `existing` (a same-worktree re-claim, or the
150
+ * worktree-inherits-session path at `colab worktree new`) — false on a `--force` takeover from a
151
+ * DIFFERENT holder.
152
+ *
153
+ * Rule: a blank incoming `branch`/`session`/`sessionName` keeps the existing value, but ONLY when
154
+ * `sameHolder` — a real new holder (a takeover) must never silently inherit a displaced holder's
155
+ * session, which would be identity forgery under the fine `#267` setting; a takeover is announced
156
+ * (`printTakeover`) and its record should honestly reflect what the new holder actually supplied.
157
+ * `worktree` is always copied from `incoming` verbatim — it is never inherited (see module doc).
158
+ */
159
+ function mergeClaimRecord(existing, incoming, { sameHolder } = {}) {
160
+ const merged = { ...incoming };
161
+ if (existing && sameHolder) {
162
+ for (const field of ['branch', 'session', 'sessionName']) {
163
+ if (!merged[field] && existing[field]) merged[field] = existing[field];
164
+ }
165
+ }
166
+ return merged;
167
+ }
168
+
169
+ /**
170
+ * Does `v` look like a session ID a consumer could actually JOIN on — a URL, or a `session_…`
171
+ * token embedded in one (#306)? The repo's ONE answer to that question: `parseSessionField`
172
+ * (tools/colab) decodes a claim comment's `· session <field>` tail with exactly this test, and
173
+ * `warnWeakIdentity` warns with it. Two copies of a shape rule drift, and this one decides
174
+ * whether a hold can ever be released by its own owner, so there is one.
175
+ *
176
+ * ⚠ This is a SHAPE heuristic and deliberately not a gate. `requirePlaceIdentity`'s own refusal
177
+ * text promises `--session <url-or-any-stable-id>`, and the fleet has real callers (and six of
178
+ * this repo's own test fixtures) using bare stable ids like `sess-agent`. A false here means
179
+ * "warn the caller they may have passed a session NAME by mistake" — never "refuse the write".
180
+ * Rejecting a non-URL would break that documented contract and every such adopter.
181
+ *
182
+ * False for '' / null: absence is `warnWeakIdentity`'s and `requirePlaceIdentity`'s subject
183
+ * (#11/#242), never this predicate's — callers test blankness first.
184
+ */
185
+ function looksLikeSessionId(v) {
186
+ const s = String(v == null ? '' : v).trim();
187
+ if (!s) return false;
188
+ return /^https?:\/\//.test(s) || /session_[\w-]+/.test(s);
189
+ }
190
+
191
+ module.exports = {
192
+ DEFAULT_COMPONENTS, FINE_COMPONENTS,
193
+ claimIdentityProblem, components, identityString, sameClaimant, mergeClaimRecord,
194
+ looksLikeSessionId, isIntentSession, sameHost,
195
+ };
@@ -0,0 +1,208 @@
1
+ 'use strict';
2
+ /**
3
+ * #350 — the core-path review rule for `colab ship` (CONVENTIONS.md §2, "Core paths").
4
+ *
5
+ * A branch whose diff touches a path the TARGET's CODEOWNERS covers does not squash directly: ship
6
+ * opens a PR and pauses, and landing resumes once an account other than the author has approved the
7
+ * branch's current head. Everything else keeps the machine-only landing.
8
+ *
9
+ * "Core" is whatever CODEOWNERS covers. The handbook tells a repo to write that file BY KIND (the
10
+ * gate, merge behaviour, permissions, the descriptor, irreversible state), so this module adds no
11
+ * kind list of its own. A second list here would be a second source of truth for the same fact.
12
+ *
13
+ * This module is PURE: text and arrays in, verdicts out. All git and gh I/O stays in the CLI, where
14
+ * `tools/colab` has no test harness. The same split docs-only.js uses.
15
+ *
16
+ * Every doubt resolves toward "the rule is active". A false "active" costs one PR and one approval.
17
+ * A false "inert" lands a change to the gate that nobody else looked at.
18
+ */
19
+
20
+ /** Where the forge looks for the file, in its own order. The first one present wins. */
21
+ const CODEOWNERS_PATHS = Object.freeze(['.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS']);
22
+
23
+ /**
24
+ * Parse CODEOWNERS text into `{ rules: [{ pattern, owners, line, re }], warnings: [] }`.
25
+ * `re` is null for a pattern this module will not match (see `compile`), and such a line is recorded
26
+ * in `warnings`, never silently widened into a match.
27
+ */
28
+ function parse(text) {
29
+ const rules = [];
30
+ const warnings = [];
31
+ String(text || '').split(/\r?\n/).forEach((raw, i) => {
32
+ // An unescaped `#` starts a comment. `\#` is a literal hash.
33
+ let s = '';
34
+ for (let k = 0; k < raw.length; k++) {
35
+ if (raw[k] === '\\' && raw[k + 1] === '#') { s += '#'; k++; continue; }
36
+ if (raw[k] === '#') break;
37
+ s += raw[k];
38
+ }
39
+ const parts = s.trim().split(/\s+/).filter(Boolean);
40
+ if (!parts.length) return;
41
+ const [pattern, ...owners] = parts;
42
+ const re = compile(pattern);
43
+ if (!re) warnings.push(`line ${i + 1}: "${pattern}" uses syntax the forge does not support in CODEOWNERS (! or [ ]) — it matches nothing`);
44
+ rules.push({ pattern, owners, line: i + 1, re });
45
+ });
46
+ return { rules, warnings };
47
+ }
48
+
49
+ /**
50
+ * Compile one CODEOWNERS pattern (the forge's gitignore subset) to a RegExp over repo-relative paths.
51
+ * - a leading `/` anchors at the repo root; so does any `/` in the middle;
52
+ * - a pattern with no `/` except a trailing one matches at any depth;
53
+ * - a pattern that names a directory also covers everything under it;
54
+ * - `*` does not cross `/`, `**` does, `?` is one non-`/` character.
55
+ * Negation (`!`) and character ranges (`[ ]`) are not supported by the forge here: returns null.
56
+ */
57
+ function compile(pattern) {
58
+ let p = String(pattern);
59
+ if (p.startsWith('!') || /[[\]]/.test(p)) return null;
60
+ const dirOnly = p.endsWith('/');
61
+ if (dirOnly) p = p.slice(0, -1);
62
+ const anchored = p.startsWith('/') || p.includes('/');
63
+ if (p.startsWith('/')) p = p.slice(1);
64
+ if (p === '' || p === '*' || p === '**') return /^.+$/;
65
+ let body = '';
66
+ for (let i = 0; i < p.length; i++) {
67
+ const c = p[i];
68
+ if (c === '*' && p[i + 1] === '*') {
69
+ i++;
70
+ if (p[i + 1] === '/') { i++; body += '(?:.*/)?'; } else { body += '.*'; }
71
+ } else if (c === '*') {
72
+ body += '[^/]*';
73
+ } else if (c === '?') {
74
+ body += '[^/]';
75
+ } else {
76
+ body += c.replace(/[.+^${}()|\\]/g, '\\$&');
77
+ }
78
+ }
79
+ const lead = anchored ? '^' : '^(?:.*/)?';
80
+ // A name matches the file itself, or — as a directory — everything under it. `dir/*` stops at one
81
+ // level because its last segment is `[^/]*` and there is no second chance after it.
82
+ const tail = /\[\^\/\]\*$/.test(body) && !/\.\*$/.test(body) ? '$' : '(?:/.*)?$';
83
+ return new RegExp(lead + body + (dirOnly ? '/.*$' : tail));
84
+ }
85
+
86
+ /** Owners of `path` under `rules`: the LAST matching rule wins. `[]` = unowned (or carved out). */
87
+ function ownerOf(rules, p) {
88
+ let owners = [];
89
+ for (const r of rules || []) if (r.re && r.re.test(p)) owners = r.owners;
90
+ return owners;
91
+ }
92
+
93
+ /** The subset of `paths` that CODEOWNERS covers with at least one owner, each with its owners. */
94
+ function corePaths(rules, paths) {
95
+ const out = [];
96
+ for (const p of [...new Set(paths || [])]) {
97
+ const owners = ownerOf(rules, p);
98
+ if (owners.length) out.push({ path: p, owners });
99
+ }
100
+ return out;
101
+ }
102
+
103
+ const norm = (s) => String(s || '').replace(/^@/, '').toLowerCase();
104
+
105
+ /**
106
+ * Is the rule inert on this repo? `authors` = the logins that count as the author of this landing
107
+ * (the forge login running ship, plus a branch-prefix login when it differs).
108
+ *
109
+ * Inert when the file owns nothing, or when every owner token is one of the authors. That is the
110
+ * single-operator repo, which lands as it does today. Anything else is active: another login, a team
111
+ * (`@org/team`, which cannot be expanded without a network call, so it counts as someone else), an
112
+ * email address. With no known author at all the rule is never inert while anything is owned.
113
+ */
114
+ function inert(rules, authors) {
115
+ const owned = (rules || []).filter((r) => r.owners.length);
116
+ if (!owned.length) return { inert: true, reason: 'CODEOWNERS owns no path' };
117
+ const me = new Set((authors || []).filter(Boolean).map(norm));
118
+ if (!me.size) return { inert: false, reason: 'the author\'s forge login is unknown, so nobody can be ruled out' };
119
+ const others = [...new Set(owned.flatMap((r) => r.owners).filter((o) => !me.has(norm(o))))];
120
+ if (!others.length) return { inert: true, reason: `CODEOWNERS names only the author (${[...me].map((m) => '@' + m).join(', ')})` };
121
+ return { inert: false, reason: `CODEOWNERS names ${others.join(', ')}` };
122
+ }
123
+
124
+ /**
125
+ * Has a PR been approved by someone other than its author, AT `headSha`?
126
+ *
127
+ * `reviews`: the forge's review list, `[{ author: { login }, state, submittedAt, commit: { oid } }]`.
128
+ * COMMENTED and PENDING carry no verdict and are dropped; the rest keep only the LATEST per reviewer.
129
+ * Any latest CHANGES_REQUESTED blocks. Otherwise an APPROVED from a reviewer who is neither the PR's
130
+ * author nor any of `authors`, whose commit is `headSha`, approves. An approval of an older head is
131
+ * stale: the reviewer did not see what would land.
132
+ *
133
+ * Fleets that share ONE forge account cannot approve each other through this — to the forge they are
134
+ * one author, and so they are here. That is the rule working, not a gap: a factory is an account.
135
+ */
136
+ function approvalVerdict(reviews, { prAuthor, authors = [], headSha }) {
137
+ const excluded = new Set([prAuthor, ...authors].filter(Boolean).map(norm));
138
+ const latest = new Map();
139
+ const sorted = [...(reviews || [])].sort((a, b) => String(a.submittedAt || '').localeCompare(String(b.submittedAt || '')));
140
+ for (const r of sorted) {
141
+ if (!r || !r.author || !r.author.login) continue;
142
+ if (r.state !== 'APPROVED' && r.state !== 'CHANGES_REQUESTED' && r.state !== 'DISMISSED') continue;
143
+ latest.set(norm(r.author.login), r);
144
+ }
145
+ const blocking = [...latest.values()].filter((r) => r.state === 'CHANGES_REQUESTED');
146
+ if (blocking.length) return { ok: false, by: null, reason: `changes requested by ${blocking.map((r) => r.author.login).join(', ')}` };
147
+ const approvals = [...latest.values()].filter((r) => r.state === 'APPROVED');
148
+ const foreign = approvals.filter((r) => !excluded.has(norm(r.author.login)));
149
+ const current = foreign.find((r) => r.commit && r.commit.oid && headSha && r.commit.oid === headSha);
150
+ if (current) return { ok: true, by: current.author.login, reason: `approved by ${current.author.login} at ${String(headSha).slice(0, 7)}` };
151
+ if (foreign.length) return { ok: false, by: null, reason: `approval by ${foreign.map((r) => r.author.login).join(', ')} is for an older head, not ${String(headSha || '?').slice(0, 7)} — stale` };
152
+ if (approvals.length) return { ok: false, by: null, reason: 'only the author\'s own account has approved — a non-author approval is required' };
153
+ return { ok: false, by: null, reason: 'no approval yet' };
154
+ }
155
+
156
+ /**
157
+ * #351 — the core-path verdict for a BRANCHLESS trunk-direct unit (`colab ship --direct`).
158
+ *
159
+ * A branch that touches a core path pauses on a PR (#350). A trunk-direct unit has no branch and so no
160
+ * PR, and its commits are already on trunk. Ruling A on #351: `ship --direct` refuses to close such a
161
+ * unit, and the operator redoes the change on a branch, where #350's review applies. So there are
162
+ * only three verdicts here: 'inert' | 'not-core' | 'refuse'. No 'pending', no 'approved'.
163
+ *
164
+ * `files`: the CODEOWNERS to honour, as `{ path, ref, text }` or null. The caller passes the one on
165
+ * trunk BEFORE the unit's first commit and the one on trunk NOW. For `--direct` the target already
166
+ * contains the unit, so reading only the current file would let a unit exempt itself by deleting or
167
+ * narrowing CODEOWNERS in its own commit. So a path is core if EITHER active file covers it, and the
168
+ * rule is inert only when every file present is inert. Identical texts count once.
169
+ * `changed`: every path the unit's commits touched, or null when they could not be listed. Null
170
+ * refuses while the rule is active: an unbounded unit cannot be shown to avoid core paths.
171
+ */
172
+ function directVerdict({ files, authors, changed }) {
173
+ const out = { active: false, inertReason: null, codeownersPath: null, warnings: [], corePaths: [], verdict: 'inert', detail: '' };
174
+ const seen = new Set();
175
+ const present = (files || []).filter((f) => f && !seen.has(f.text) && seen.add(f.text));
176
+ if (!present.length) { out.inertReason = 'no CODEOWNERS on trunk before or after the unit'; out.detail = `inert: ${out.inertReason}`; return out; }
177
+ const byPath = new Map();
178
+ const inertReasons = [];
179
+ const activeReasons = [];
180
+ for (const f of present) {
181
+ const { rules, warnings } = parse(f.text);
182
+ for (const w of warnings) out.warnings.push(`${f.path}@${f.ref}: ${w}`);
183
+ const iv = inert(rules, authors);
184
+ if (iv.inert) { inertReasons.push(`${f.path}@${f.ref}: ${iv.reason}`); continue; }
185
+ out.active = true;
186
+ if (!out.codeownersPath) out.codeownersPath = f.path;
187
+ activeReasons.push(iv.reason);
188
+ for (const c of corePaths(rules, changed || [])) {
189
+ const prev = byPath.get(c.path);
190
+ byPath.set(c.path, prev ? [...new Set([...prev, ...c.owners])] : c.owners);
191
+ }
192
+ }
193
+ if (!out.active) { out.inertReason = inertReasons.join('; '); out.detail = `inert: ${out.inertReason}`; return out; }
194
+ if (changed === null || changed === undefined) {
195
+ out.verdict = 'refuse';
196
+ out.detail = `the core-path rule is active (${activeReasons[0]}) and the unit's commits could not be listed — cannot show it avoids core paths`;
197
+ return out;
198
+ }
199
+ out.corePaths = [...byPath].map(([p, owners]) => ({ path: p, owners }));
200
+ if (!out.corePaths.length) { out.verdict = 'not-core'; out.detail = `no core path touched (${activeReasons[0]})`; return out; }
201
+ const list = out.corePaths.map((c) => c.path);
202
+ const shown = list.slice(0, 3).join(', ') + (list.length > 3 ? ` (+${list.length - 3})` : '');
203
+ out.verdict = 'refuse';
204
+ out.detail = `${list.length} core path(s): ${shown} — a trunk-direct unit has no PR to review them; redo the change on a branch (#351)`;
205
+ return out;
206
+ }
207
+
208
+ module.exports = { CODEOWNERS_PATHS, parse, compile, ownerOf, corePaths, inert, approvalVerdict, directVerdict };
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+ /**
3
+ * Cheap, repo-local evidence that SOMETHING consumes a repo — a version-shaped git tag, or a
4
+ * committed deploy path. Extracted from `audit/audit.mjs` (#137's falsifiers) so `colab adopt`
5
+ * (#199) can reuse the identical detection without a second implementation: `install.sh` freezes
6
+ * `tools/colab` + `tools/lib/` only, nothing under `audit/` is frozen, so anything both the audit
7
+ * and the CLI need has to live here, not there.
8
+ *
9
+ * CommonJS, matching stamp.js / axis-authority.js: `audit/audit.mjs` (ESM) consumes this through
10
+ * its existing `createRequire`; `tools/colab` (CJS) can `require` it directly. One implementation,
11
+ * not two, for the identical reason every other cross-tool reading in this handbook lives in one
12
+ * place — two readings of "does anything consume this repo" disagreeing is the two-places-drift
13
+ * disease this handbook exists to kill.
14
+ *
15
+ * This module only ever GATHERS evidence — it never decides severity, never reads `exposureRaw` or
16
+ * `channelsRaw`, and never says what a caller should conclude from what it finds. That policy (warn
17
+ * vs fail, the 2-of-5 falsifier reach, why `exposure: self` gets nothing) is the audit's own and
18
+ * stays in `audit/audit.mjs` — see its "exposure/channels falsifiers" comment block.
19
+ */
20
+
21
+ // "v2.1.0", "1.4", "v3.0.0-rc1" count; "backup-2024" does not — no dot-separated numeric
22
+ // parts, so nothing about it claims to be a release. Calibration knob, not a settled
23
+ // grammar: real-world tag schemes vary, and a repo with an unusual-but-real scheme is a
24
+ // false negative here (silence), never a false positive.
25
+ const VERSION_TAG_RE = /^v?\d+\.\d+(?:\.\d+)*(?:[-+][0-9A-Za-z.]+)*$/;
26
+
27
+ function versionShapedTags(tags) {
28
+ return (tags || []).filter((t) => VERSION_TAG_RE.test(t));
29
+ }
30
+
31
+ // A `deploy`/`release` basename, any single extension (or none — a plain shell script often
32
+ // carries none). Matched only against a NON-recursive listing of the repo root, scripts/,
33
+ // and bin/ — the exclusion of templates/, examples/, docs/ in #137's plan is achieved simply
34
+ // by never looking there, not by an exclude list.
35
+ const DEPLOY_BASENAME_RE = /^(deploy|release)(\.[A-Za-z0-9]+)?$/i;
36
+
37
+ // Cheap repo-local evidence that something OTHER than "nothing" consumes this repo. Never
38
+ // throws, never returns null itself — every source it reads (tags(), listDir()) already
39
+ // degrades to null/[] on failure, and an unreadable source just means less evidence, not an
40
+ // error. Takes `workflows` from the caller (already listed by the tier checks) rather than
41
+ // re-listing .github/workflows — the "zero new IO" half of F5.
42
+ function consumerEvidence(src, workflows) {
43
+ const versionTags = versionShapedTags(src.tags());
44
+
45
+ const deployPaths = [];
46
+ for (const wf of workflows) {
47
+ if (/^(deploy|release)[-.]/.test(wf)) deployPaths.push(`.github/workflows/${wf}`);
48
+ }
49
+ for (const dir of ["", "scripts", "bin"]) {
50
+ for (const f of src.listDir(dir)) {
51
+ if (DEPLOY_BASENAME_RE.test(f)) deployPaths.push(dir ? `${dir}/${f}` : f);
52
+ }
53
+ }
54
+
55
+ return { versionTags, deployPaths };
56
+ }
57
+
58
+ // One line of prose describing whatever consumerEvidence() found, or "" when it found
59
+ // nothing — the caller stays silent on "".
60
+ function describeEvidence(evidence) {
61
+ const bits = [];
62
+ if (evidence.versionTags.length) {
63
+ const [first, ...rest] = evidence.versionTags;
64
+ bits.push(`a release artifact exists (tag ${first}${rest.length ? ` +${rest.length} more` : ""})`);
65
+ }
66
+ if (evidence.deployPaths.length) {
67
+ const shown = evidence.deployPaths.slice(0, 3);
68
+ const more = evidence.deployPaths.length > 3 ? ", …" : "";
69
+ bits.push(`a committed deploy path exists (${shown.join(", ")}${more})`);
70
+ }
71
+ return bits.join("; ");
72
+ }
73
+
74
+ module.exports = { VERSION_TAG_RE, versionShapedTags, DEPLOY_BASENAME_RE, consumerEvidence, describeEvidence };
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+ /**
3
+ * Close a container with its last child (#371) — the pure half.
4
+ *
5
+ * THE DEFECT. A dependency review of one adopting repo's open backlog found five open
6
+ * containers (epics) whose every child was closed, and one of them still carried a
7
+ * `delivery:code` label. Nothing closed them: a child's squash-merge closes the CHILD (its
8
+ * `Closes #N`), and `code-ship` B2c said "never close the epic" — a rule written for
9
+ * hand-maintained checklists, where boxes running out does not prove work running out. On
10
+ * NATIVE sub-issues that reasoning is weaker (GitHub maintains `subIssuesSummary`, so "every
11
+ * child is closed" is a fact, not a hand-kept claim), and an open container nobody will ever
12
+ * close is backlog noise every triage pass re-reads.
13
+ *
14
+ * THE RULE THIS MODULE DECIDES (CONVENTIONS.md §5, *Epics*): after a ship closes an issue, look
15
+ * at its native parent. Close the parent, with evidence, in the same step, when ALL hold:
16
+ *
17
+ * - it is a container — carries the `epic` label (the label is normative; a title prefix or a
18
+ * sub-issue count only corroborates, CONVENTIONS.md §5 *Epics*);
19
+ * - it has native sub-issues and every one of them is closed;
20
+ * - its body holds no unticked checklist line. An unticked `- [ ]` on an epic is an item
21
+ * somebody listed and nobody filed as a sub-issue yet — the "two phases whose issues are not
22
+ * written yet" B2c's rule was protecting. It is reported, never closed over;
23
+ * - it is not a release tracking record (`<!-- colab:release …` body) — `colab release
24
+ * finalize` owns that record's lifecycle, not a child's ship.
25
+ *
26
+ * A parent WITHOUT the `epic` label whose sub-issues are all closed is a FINDING, not a close:
27
+ * it may be a real task that merely has children, and whether it is done is a human's reading.
28
+ *
29
+ * VERDICTS (every one but `close` leaves the parent exactly as it is):
30
+ *
31
+ * close all conditions above hold
32
+ * unknown the parent could not be read — never "nothing to do", never closed
33
+ * already-closed nothing to do
34
+ * release-record a release tracking issue — owned by `colab release finalize`
35
+ * no-sub-issues no native children (a hand checklist at most) — B2c's limits still apply
36
+ * children-open at least one sub-issue is still open — the normal state of a live epic
37
+ * not-container every child closed, but no `epic` label — report for a human
38
+ * unfiled-items every child closed, but the body still lists unticked items — report
39
+ *
40
+ * Fail toward keeping open, the same asymmetry `group-labels.js` states for its own delete: a
41
+ * container closed early buries unwritten work behind a closed issue nobody browses, while one
42
+ * left open costs a line in the next triage report.
43
+ */
44
+
45
+ const { DELIVERY_LABEL_PREFIX } = require('./labels.js');
46
+
47
+ const EPIC_LABEL = 'epic';
48
+
49
+ /** A release tracking issue's body opens with this marker (`colab release finalize`, #339). */
50
+ const RELEASE_RECORD_RE = /^\s*<!--\s*colab:release\b/;
51
+
52
+ /** An UNTICKED GitHub checklist line anywhere in the body — `- [ ] …` / `* [ ] …`. */
53
+ const UNTICKED_RE = /^\s*[-*]\s*\[ \]\s*(.+)$/;
54
+
55
+ function labelNames(labels) {
56
+ return (labels || []).map((l) => (l && typeof l === 'object' ? l.name : l)).map((n) => String(n));
57
+ }
58
+
59
+ /** The unticked checklist lines in a body, trimmed, in document order. Fenced code is skipped —
60
+ * a `- [ ]` inside a ``` block is an example someone quoted, not an item they listed. */
61
+ function untickedItems(body) {
62
+ const out = [];
63
+ let fenced = false;
64
+ for (const line of String(body || '').split('\n')) {
65
+ if (/^\s*(```|~~~)/.test(line)) { fenced = !fenced; continue; }
66
+ if (fenced) continue;
67
+ const m = UNTICKED_RE.exec(line);
68
+ if (m) out.push(m[1].trim());
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /**
74
+ * Classify ONE parent issue after a child of it closed.
75
+ *
76
+ * @param {object|null} parent `gh issue view <P> --json number,state,labels,body,subIssuesSummary`,
77
+ * or null when that read failed (never "no parent" — the caller
78
+ * only calls this once it knows a parent exists).
79
+ * @returns {{verdict:string, number:number|null, total:number, completed:number, unticked:string[]}}
80
+ */
81
+ function classifyContainer(parent) {
82
+ const base = { number: null, total: 0, completed: 0, unticked: [] };
83
+ if (!parent || typeof parent !== 'object') return { ...base, verdict: 'unknown' };
84
+ const number = Number.isInteger(parent.number) ? parent.number : null;
85
+ const s = parent.subIssuesSummary;
86
+ const total = s && Number.isInteger(s.total) ? s.total : null;
87
+ const completed = s && Number.isInteger(s.completed) ? s.completed : null;
88
+ const out = { ...base, number, total: total || 0, completed: completed || 0 };
89
+
90
+ if (String(parent.state || '').toUpperCase() === 'CLOSED') return { ...out, verdict: 'already-closed' };
91
+ // Anything we cannot prove is open-and-well-formed is `unknown`: a missing state or summary is
92
+ // a read we did not get, and the bias is toward leaving the container alone.
93
+ if (String(parent.state || '').toUpperCase() !== 'OPEN' || total === null || completed === null || number === null) {
94
+ return { ...out, verdict: 'unknown' };
95
+ }
96
+ if (RELEASE_RECORD_RE.test(String(parent.body || ''))) return { ...out, verdict: 'release-record' };
97
+ if (total === 0) return { ...out, verdict: 'no-sub-issues' };
98
+ if (completed < total) return { ...out, verdict: 'children-open' };
99
+ if (!labelNames(parent.labels).includes(EPIC_LABEL)) return { ...out, verdict: 'not-container' };
100
+ const unticked = untickedItems(parent.body);
101
+ if (unticked.length) return { ...out, unticked, verdict: 'unfiled-items' };
102
+ return { ...out, verdict: 'close' };
103
+ }
104
+
105
+ /**
106
+ * `delivery:*` labels on a container — a finding (#371): a container has no deliverable of its
107
+ * own, so a delivery label on one says a scheduler may treat the map as the territory. Returns the
108
+ * offending label names ([] when the issue is not an epic, or carries none).
109
+ */
110
+ function containerDeliveryLabels(labels) {
111
+ const names = labelNames(labels);
112
+ if (!names.includes(EPIC_LABEL)) return [];
113
+ return names.filter((n) => n.startsWith(DELIVERY_LABEL_PREFIX));
114
+ }
115
+
116
+ /** The evidence comment posted on a container as it is closed. One line, issue-specific only. */
117
+ function containerCloseComment({ child, sha, total, target }) {
118
+ const via = child ? `its last open sub-issue #${child} shipped` : 'its last open sub-issue closed';
119
+ const at = sha ? ` to ${target || 'trunk'} at ${sha}` : '';
120
+ return `📦 Closed by colab ship — ${via}${at}; all ${total} sub-issue(s) are closed and the body lists no unticked item (#371).`;
121
+ }
122
+
123
+ /** One report line for a verdict that is NOT `close` but still worth a human's eye; null otherwise. */
124
+ function containerFinding(c) {
125
+ const n = c.number !== null ? `#${c.number}` : 'parent';
126
+ switch (c.verdict) {
127
+ case 'not-container':
128
+ return `${n}: all ${c.total} sub-issue(s) closed, but it is not labelled \`epic\` — close it by hand if it is a container`;
129
+ case 'unfiled-items':
130
+ return `${n}: all ${c.total} sub-issue(s) closed, but ${c.unticked.length} unticked item(s) remain in its body — file them as sub-issues or tick them, then close`;
131
+ case 'unknown':
132
+ return `${n}: could not read the parent — container close skipped`;
133
+ default:
134
+ return null;
135
+ }
136
+ }
137
+
138
+ module.exports = {
139
+ EPIC_LABEL, RELEASE_RECORD_RE,
140
+ untickedItems, classifyContainer, containerDeliveryLabels, containerCloseComment, containerFinding,
141
+ };