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

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +312 -3
  3. package/README.vi.md +281 -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 +13806 -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 +278 -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-endpoint.js +170 -0
  63. package/tools/lib/notify.js +188 -0
  64. package/tools/lib/npm-publish-guard.js +242 -0
  65. package/tools/lib/orphan-worktree.js +127 -0
  66. package/tools/lib/owner-branch.js +182 -0
  67. package/tools/lib/place.js +782 -0
  68. package/tools/lib/ports.js +167 -0
  69. package/tools/lib/procs.js +185 -0
  70. package/tools/lib/readiness.js +240 -0
  71. package/tools/lib/records.js +185 -0
  72. package/tools/lib/refs-brake.js +95 -0
  73. package/tools/lib/release-channel.js +99 -0
  74. package/tools/lib/release-cut.js +822 -0
  75. package/tools/lib/release-finalize.js +521 -0
  76. package/tools/lib/release-policy.js +358 -0
  77. package/tools/lib/release-tag.js +225 -0
  78. package/tools/lib/ship-batch.js +277 -0
  79. package/tools/lib/ship-roles.js +71 -0
  80. package/tools/lib/ship-target-sync.js +181 -0
  81. package/tools/lib/shipguard.js +317 -0
  82. package/tools/lib/shipped-branch.js +56 -0
  83. package/tools/lib/solo.js +213 -0
  84. package/tools/lib/squash.js +515 -0
  85. package/tools/lib/stale-base.js +70 -0
  86. package/tools/lib/stamp.js +740 -0
  87. package/tools/lib/state.js +262 -0
  88. package/tools/lib/teardown.js +83 -0
  89. package/tools/lib/trust-humans.js +104 -0
  90. package/tools/lib/util.js +98 -0
  91. package/tools/lib/wake.js +188 -0
  92. package/tools/lib/workflow-triggers.js +273 -0
  93. package/tools/lib/writes-authority.js +237 -0
  94. package/tools/lib/yaml.js +101 -0
  95. package/bin/cli.js +0 -3
@@ -0,0 +1,242 @@
1
+ 'use strict';
2
+ /**
3
+ * The private-repo / public-npm rule (#432, part of #420).
4
+ *
5
+ * Owner ruling 2026-10-02: `@<org>` on public npm is always public, so a PRIVATE repository
6
+ * never publishes to public npm. Private apps are installed from git
7
+ * (`npx github:<org>/<repo>#<tag>`), where repository access is the access control.
8
+ *
9
+ * This module is pure: it takes a reader and the repository's visibility and returns findings.
10
+ * Visibility comes from the GitHub API at the caller (never a local guess).
11
+ *
12
+ * exposure(...) -> { problems: string[] } every way this repo could reach public npm
13
+ * findings(...) -> [{ level, text }] what the audit reports given visibility
14
+ *
15
+ * Two kinds of problem, both only a finding when the repo is private:
16
+ * 1. a package.json (root or workspace member) without `"private": true`, or whose
17
+ * `publishConfig.registry` is the public registry;
18
+ * 2. a workflow step that publishes to registry.npmjs.org.
19
+ */
20
+
21
+ const PUBLIC_REGISTRY = /registry\.(npmjs\.org|yarnpkg\.com)/i;
22
+
23
+ // `npm publish`, `pnpm publish`, `yarn publish`, `yarn npm publish`, `bun publish`.
24
+ const PUBLISH_CMD = /(^|[\s;&|(])(npm|pnpm|bun|yarn(\s+npm)?)\s+publish\b/;
25
+ const PUBLISH_ACTION = /\buses:\s*['"]?[\w.-]*\/?[\w.-]*npm-publish\b/i;
26
+
27
+ function stripComment(line) {
28
+ return line.replace(/(^|\s)#.*$/, '');
29
+ }
30
+
31
+ /** Workflow lines that publish to the public registry. Returns [{ wf, line, text }]. */
32
+ function workflowPublishes(workflows, readFile) {
33
+ const out = [];
34
+ for (const wf of workflows || []) {
35
+ const text = readFile(`.github/workflows/${wf}`);
36
+ if (!text) continue;
37
+ text.split('\n').forEach((raw, i) => {
38
+ const line = stripComment(raw);
39
+ const isCmd = PUBLISH_CMD.test(line);
40
+ const isAction = PUBLISH_ACTION.test(line);
41
+ if (!isCmd && !isAction) return;
42
+ if (isCmd) {
43
+ if (/--dry-run\b/.test(line)) return; // cannot publish
44
+ const reg = line.match(/--registry[=\s]+(\S+)/);
45
+ if (reg && !PUBLIC_REGISTRY.test(reg[1])) return; // pointed elsewhere
46
+ }
47
+ out.push({ wf, line: i + 1, text: line.trim() });
48
+ });
49
+ }
50
+ return out;
51
+ }
52
+
53
+ function parseJson(text) {
54
+ try { return JSON.parse(text); } catch (_) { return undefined; }
55
+ }
56
+
57
+ function expandPattern(pat, listDir, readFile) {
58
+ const p = String(pat).replace(/^\.\//, '').replace(/\/+$/, '');
59
+ if (!p || p.startsWith('!')) return [];
60
+ if (p.endsWith('/*') || p.endsWith('/**')) {
61
+ const base = p.replace(/\/\*+$/, '');
62
+ return listDir(base)
63
+ .map((d) => `${base}/${d}`)
64
+ .filter((d) => readFile(`${d}/package.json`) != null);
65
+ }
66
+ return readFile(`${p}/package.json`) != null ? [p] : [];
67
+ }
68
+
69
+ function workspacePatterns(rootPkg, readFile) {
70
+ const out = [];
71
+ const ws = rootPkg && rootPkg.workspaces;
72
+ if (Array.isArray(ws)) out.push(...ws);
73
+ else if (ws && Array.isArray(ws.packages)) out.push(...ws.packages);
74
+ const pnpm = readFile('pnpm-workspace.yaml');
75
+ if (pnpm) {
76
+ for (const m of pnpm.matchAll(/^\s*-\s*['"]?([^'"#\n]+?)['"]?\s*(#.*)?$/gm)) out.push(m[1]);
77
+ }
78
+ return out;
79
+ }
80
+
81
+ /** Every package.json that could be published: root plus workspace members. */
82
+ function manifests(readFile, listDir) {
83
+ const out = [];
84
+ const rootText = readFile('package.json');
85
+ if (rootText == null) return out;
86
+ const root = parseJson(rootText);
87
+ out.push({ path: 'package.json', pkg: root, unparsed: root === undefined });
88
+ const seen = new Set(['package.json']);
89
+ for (const pat of workspacePatterns(root, readFile)) {
90
+ for (const dir of expandPattern(pat, listDir, readFile)) {
91
+ const p = `${dir}/package.json`;
92
+ if (seen.has(p)) continue;
93
+ seen.add(p);
94
+ const pkg = parseJson(readFile(p));
95
+ out.push({ path: p, pkg, unparsed: pkg === undefined });
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+
101
+ /** Everything in this repo that could reach public npm. */
102
+ function exposure({ readFile, listDir, workflows }) {
103
+ const problems = [];
104
+ for (const m of manifests(readFile, listDir)) {
105
+ if (m.unparsed || !m.pkg || typeof m.pkg !== 'object') continue; // the toolchain check reports unparsable JSON
106
+ if (m.pkg.private !== true) {
107
+ problems.push(`${m.path} lacks "private": true`);
108
+ }
109
+ const reg = m.pkg.publishConfig && m.pkg.publishConfig.registry;
110
+ if (typeof reg === 'string' && PUBLIC_REGISTRY.test(reg)) {
111
+ problems.push(`${m.path} publishConfig.registry points at ${reg}`);
112
+ }
113
+ }
114
+ for (const p of workflowPublishes(workflows, readFile)) {
115
+ problems.push(`.github/workflows/${p.wf}:${p.line} publishes to public npm (\`${p.text}\`)`);
116
+ }
117
+ return { problems };
118
+ }
119
+
120
+ const RULE = 'a private repository never publishes to public npm — install private apps from git (`npx github:<org>/<repo>#<tag>`) and set "private": true (CONVENTIONS.md, owner ruling 2026-10-02)';
121
+
122
+ /**
123
+ * @param visibility 'public' | 'private' | 'internal' | null (unknown)
124
+ * Public repos pass. Unknown visibility is reported (warn), never passed — but only when there is
125
+ * something it would matter for, so a repo with no npm surface stays silent.
126
+ */
127
+ function findings({ readFile, listDir, workflows, visibility }) {
128
+ if (visibility === 'public') return [];
129
+ const { problems } = exposure({ readFile, listDir, workflows });
130
+ if (!problems.length) return [];
131
+ if (visibility === 'private' || visibility === 'internal') {
132
+ return problems.map((t) => ({ level: 'fail', text: `${t} — ${RULE}` }));
133
+ }
134
+ return [{
135
+ level: 'warn',
136
+ text: `repository visibility could not be read, so the private-repo npm rule could not be checked (${problems.length} candidate finding(s): ${problems.join('; ')}) — ${RULE}`,
137
+ }];
138
+ }
139
+
140
+ // ---- #442: GitHub Release assets are not an install path ------------------------------------
141
+ //
142
+ // CONVENTIONS.md §6, *Distribution*: every distributed tool installs with `npx`. A private compiled
143
+ // tool ships its binaries as dist refs in its own repo (templates/dist-refs.yml) and installs with
144
+ // `npx github:<org>/<repo>#vX.Y.Z`; a private repo uploading binaries as Release assets is asking
145
+ // every user for the `gh` CLI (or a token) to install it. Advisory: a Release asset can be a
146
+ // legitimate by-product (an SBOM, a changelog), so this warns and never fails.
147
+
148
+ // Actions that upload Release assets unconditionally, and those that do only with a files key.
149
+ const ASSET_ACTION_ALWAYS = /\buses:\s*['"]?(actions\/upload-release-asset|svenstaro\/upload-release-action)\b/i;
150
+ const ASSET_ACTION_KEYED = [
151
+ { re: /\buses:\s*['"]?softprops\/action-gh-release\b/i, key: /^\s*files:\s*\S/ },
152
+ { re: /\buses:\s*['"]?ncipollo\/release-action\b/i, key: /^\s*artifacts:\s*\S/ },
153
+ ];
154
+ // `gh release create <tag> [<file>…]` flags that take a value — their value is not a file.
155
+ const GH_VALUE_FLAGS = new Set(['-n', '--notes', '-F', '--notes-file', '-t', '--title', '--target',
156
+ '--discussion-category', '--notes-start-tag', '-R', '--repo', '--fail-on-no-commits']);
157
+
158
+ function shellTokens(line) {
159
+ return (line.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/g) || []);
160
+ }
161
+
162
+ // A positional argument that is a file: a path, a glob, or a name with an extension. A bare
163
+ // expansion like "${KIND[@]}" (an array of flags, in the handbook's own release templates) is not.
164
+ function looksLikeAsset(tok) {
165
+ const t = tok.replace(/^["']|["']$/g, '');
166
+ if (/^\$\{?\w+(\[@\])?\}?$/.test(t)) return false;
167
+ return /[/*]/.test(t) || /\.[A-Za-z0-9]{1,8}(#.*)?$/.test(t);
168
+ }
169
+
170
+ // `files: ${{ env.ATTACH_ARTIFACTS == 'true' && '…' || '' }}` with `ATTACH_ARTIFACTS: "false"`
171
+ // declared in the same file — templates/release-tag.yml's opt-in, as shipped — uploads nothing.
172
+ // Flipping the switch to "true" makes it an upload again, and that is reported.
173
+ function switchedOff(line, text) {
174
+ const m = line.match(/env\.(\w+)\s*==\s*'true'/);
175
+ return !!m && new RegExp(`^\\s*${m[1]}:\\s*["']?false["']?\\s*(#.*)?$`, 'm').test(text);
176
+ }
177
+
178
+ /** `gh release create` lines that pass files, after the tag. */
179
+ function ghCreateUploads(line) {
180
+ const toks = shellTokens(line);
181
+ const at = toks.findIndex((t, i) => t === 'create' && toks[i - 1] === 'release' && toks[i - 2] === 'gh');
182
+ if (at === -1) return false;
183
+ const pos = [];
184
+ for (let i = at + 1; i < toks.length; i++) {
185
+ const t = toks[i];
186
+ if (/^[;&|]/.test(t)) break;
187
+ if (t.startsWith('-')) { if (GH_VALUE_FLAGS.has(t)) i++; continue; }
188
+ pos.push(t);
189
+ }
190
+ return pos.slice(1).some(looksLikeAsset);
191
+ }
192
+
193
+ /** Workflow lines that upload GitHub Release assets. Returns [{ wf, line, text }]. */
194
+ function releaseAssetUploads(workflows, readFile) {
195
+ const out = [];
196
+ for (const wf of workflows || []) {
197
+ const text = readFile(`.github/workflows/${wf}`);
198
+ if (!text) continue;
199
+ const lines = text.split('\n');
200
+ lines.forEach((raw, i) => {
201
+ const line = stripComment(raw);
202
+ let hit = /(^|[\s;&|(])gh\s+release\s+upload\b/.test(line) || ghCreateUploads(line) || ASSET_ACTION_ALWAYS.test(line);
203
+ if (!hit) {
204
+ const keyed = ASSET_ACTION_KEYED.find((k) => k.re.test(line));
205
+ if (keyed) {
206
+ // The step's own lines: until the next list item at this indent or shallower.
207
+ const indent = raw.search(/\S/);
208
+ const stepIndent = /^\s*-\s/.test(raw) ? indent : indent - 2;
209
+ for (let j = i + 1; j < lines.length; j++) {
210
+ const l = lines[j];
211
+ if (!l.trim()) continue;
212
+ const ind = l.search(/\S/);
213
+ if (ind <= stepIndent) break;
214
+ if (keyed.key.test(stripComment(l))) { hit = !switchedOff(l, text); break; }
215
+ }
216
+ }
217
+ }
218
+ if (hit) out.push({ wf, line: i + 1, text: line.trim() });
219
+ });
220
+ }
221
+ return out;
222
+ }
223
+
224
+ const ASSET_RULE = 'GitHub Release assets are not an install path — a private compiled tool pushes its binaries as dist refs (templates/dist-refs.yml) and installs with `npx github:<org>/<repo>#vX.Y.Z` (CONVENTIONS.md §6, Distribution, #442)';
225
+
226
+ /**
227
+ * Advisory only. Private/internal → one warn per upload site; public → nothing (a public compiled
228
+ * tool's install path is npm platform packages, and the npm job's own rules cover it); unknown
229
+ * visibility → one warn saying the rule could not be checked.
230
+ */
231
+ function assetFindings({ readFile, workflows, visibility }) {
232
+ if (visibility === 'public') return [];
233
+ const uploads = releaseAssetUploads(workflows, readFile);
234
+ if (!uploads.length) return [];
235
+ const sites = uploads.map((u) => `.github/workflows/${u.wf}:${u.line} (\`${u.text}\`)`);
236
+ if (visibility === 'private' || visibility === 'internal') {
237
+ return sites.map((s) => ({ level: 'warn', text: `${s} uploads a GitHub Release asset — ${ASSET_RULE}` }));
238
+ }
239
+ return [{ level: 'warn', text: `repository visibility could not be read, so the Release-asset install rule could not be checked (${sites.join('; ')}) — ${ASSET_RULE}` }];
240
+ }
241
+
242
+ module.exports = { exposure, findings, workflowPublishes, manifests, releaseAssetUploads, assetFindings };
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+ /**
3
+ * Detecting a directory that LOOKS like a worktree but that git never linked at all — no `.git`
4
+ * file or directory inside it, so it never appears in `git worktree list` and is therefore
5
+ * invisible to `unrecordedWorktrees()` (tools/colab), which reconciles disk against records only
6
+ * for paths git already knows about (#67's blind spot is the mirror of this one: a record naming
7
+ * a vanished directory, not a directory naming no record).
8
+ *
9
+ * #97 found the shape and fixed the actual corruption risk (an un-ignored path) plus corrected
10
+ * `code-sweep`'s completeness claim to admit this blind spot; #99 (this module) is the detector.
11
+ *
12
+ * `classifyOrphanCandidate` is pure decision logic — booleans in, a verdict out — and is
13
+ * unit-testable without a real repo or a real filesystem walk. `scanForOrphans` is the walk that
14
+ * finds candidates and calls it; it used to live only in tools/colab (a CLI entrypoint, not a
15
+ * module) with its own test-local reimplementation, which meant the shipped walk was never
16
+ * actually exercised (#107). It moved here, behind injectable fs primitives, for the same reason
17
+ * classification was extracted one layer down: so it can be called directly by both the CLI and
18
+ * its tests, with one implementation instead of two.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+
24
+ /**
25
+ * Candidate subdirectory names that might hold worktrees for a given repo, in the SAME repo-scoped
26
+ * sense `unrecordedWorktrees()` already uses — never a filesystem-wide scan. `config.worktreeSubdir`
27
+ * is a machine-global setting (`~/.colab/config.json`, see tools/lib/state.js), not per-repo, so an
28
+ * orphan left behind under a value the config used to hold (before someone ran `colab config set
29
+ * worktreeSubdir <x>`) would otherwise be permanently invisible to a scan keyed only off today's
30
+ * config. Include the current value plus known historical ones so a config change doesn't strand
31
+ * old orphans outside the swept set.
32
+ *
33
+ * @param {{worktreeSubdir?: string}} config
34
+ * @returns {string[]} deduped, in stable order (today's config value first)
35
+ */
36
+ function worktreeSubdirCandidates(config) {
37
+ const today = (config && config.worktreeSubdir) || '.worktrees';
38
+ const historical = ['.worktrees', '.claude/worktrees'];
39
+ const out = [];
40
+ for (const v of [today, ...historical]) {
41
+ if (v && !out.includes(v)) out.push(v);
42
+ }
43
+ return out;
44
+ }
45
+
46
+ /**
47
+ * Classify one candidate directory found under a `worktreeSubdirCandidates()` path.
48
+ *
49
+ * Requires BOTH `CLAUDE.md` AND `.github/project.yml` present to call something "worktree-shaped"
50
+ * — either signal alone is too weak and produces false positives that would make this detector
51
+ * noise rather than signal:
52
+ * - `CLAUDE.md` alone hits any stray doc copy (a template, an example, a docs snapshot) that has
53
+ * nothing to do with a worktree.
54
+ * - `.github/project.yml` alone hits a vendored/backup copy of a repo's config with no other
55
+ * worktree characteristics.
56
+ * Requiring both narrows the match to "a full copy of an adopting repo's tracked tree", which is
57
+ * what a real worktree actually is (mirrors audit.mjs's own `isLinkedWorktree()` reasoning: look
58
+ * for the shape colab's own worktrees have, not a single loose file).
59
+ *
60
+ * @param {object} shape
61
+ * @param {boolean} shape.hasClaudeMd
62
+ * @param {boolean} shape.hasProjectYml
63
+ * @param {boolean} shape.hasGitEntry - does `<candidate>/.git` exist (file OR directory)? If so,
64
+ * git already knows about this directory one way or another (a linked worktree, or a nested full
65
+ * clone) — not this detector's problem regardless of the other two signals.
66
+ * @returns {'orphan'|'linked'|'not-worktree-shaped'}
67
+ */
68
+ function classifyOrphanCandidate({ hasClaudeMd, hasProjectYml, hasGitEntry }) {
69
+ if (hasGitEntry) return 'linked';
70
+ if (hasClaudeMd && hasProjectYml) return 'orphan';
71
+ return 'not-worktree-shaped';
72
+ }
73
+
74
+ /**
75
+ * Walk `worktreeSubdirCandidates()` paths under each of `repos` and return every candidate
76
+ * `classifyOrphanCandidate` calls `'orphan'` — scoped exactly the way tools/colab's
77
+ * `knownReposFor()` already scopes its callers, never a filesystem-wide scan.
78
+ *
79
+ * `opts.linkedPaths`, if given, is a `Set` of resolved paths git already lists for these repos
80
+ * (`git.worktreeListDetailed()` in tools/colab, which requires git — kept out of this module so
81
+ * it stays fs-only and independently testable). A candidate in that set is skipped before
82
+ * classification even runs (#106): a worktree whose `.git` FILE was lost mid-teardown still keeps
83
+ * its admin entry in the main repo's `.git/worktrees/`, so `git worktree list` still reports it —
84
+ * `prunable (gitdir file points to non-existent location)` — even though `hasGitEntry` would read
85
+ * false. That husk satisfies every one of the three booleans the classifier tests and is not an
86
+ * orphan at all: git already knows about it, however broken its state. Without the cross-check the
87
+ * same directory would be reported twice, once by `unrecordedWorktrees()` as "recorded by git but
88
+ * not by us" and once here as "git never linked this" — two commands contradicting each other
89
+ * about the identical path.
90
+ *
91
+ * `opts.fs`, if given, replaces the three fs primitives used (`existsSync`, `readdirSync`,
92
+ * `statSync`) — the hook a fixture-backed test needs without touching global fs.
93
+ *
94
+ * @param {string[]} repos
95
+ * @param {{worktreeSubdir?: string}} config
96
+ * @param {{linkedPaths?: Set<string>, fs?: {existsSync: Function, readdirSync: Function, statSync: Function}}} [opts]
97
+ * @returns {{repo: string, path: string}[]}
98
+ */
99
+ function scanForOrphans(repos, config, opts = {}) {
100
+ const { existsSync, readdirSync, statSync } = opts.fs || fs;
101
+ const linkedPaths = opts.linkedPaths || new Set();
102
+ const out = [];
103
+ for (const repo of repos) {
104
+ for (const sub of worktreeSubdirCandidates(config)) {
105
+ const base = path.join(repo, sub);
106
+ if (!existsSync(base)) continue;
107
+ let entries;
108
+ try { entries = readdirSync(base); } catch { continue; }
109
+ for (const name of entries) {
110
+ const cand = path.join(base, name);
111
+ const resolved = path.resolve(cand);
112
+ if (linkedPaths.has(resolved)) continue; // git already lists it — not "never linked" (#106)
113
+ let isDir;
114
+ try { isDir = statSync(cand).isDirectory(); } catch { continue; }
115
+ if (!isDir) continue;
116
+ const hasGitEntry = existsSync(path.join(cand, '.git'));
117
+ const hasClaudeMd = existsSync(path.join(cand, 'CLAUDE.md'));
118
+ const hasProjectYml = existsSync(path.join(cand, '.github/project.yml'));
119
+ const verdict = classifyOrphanCandidate({ hasClaudeMd, hasProjectYml, hasGitEntry });
120
+ if (verdict === 'orphan') out.push({ repo, path: resolved });
121
+ }
122
+ }
123
+ }
124
+ return out;
125
+ }
126
+
127
+ module.exports = { worktreeSubdirCandidates, classifyOrphanCandidate, scanForOrphans };
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+ /**
3
+ * #394 (ruled D) — the owner's branch: a repo the fleet builds in but does not own.
4
+ *
5
+ * `project.yml` may declare
6
+ *
7
+ * owner:
8
+ * branch: master # the owner's branch — required when the block is present
9
+ * remote: origin # optional; the repo's own remote when absent
10
+ *
11
+ * `trunk:` stays the fleet's integration branch, and per-issue landing (`colab ship`) is unchanged.
12
+ * The owner's branch is reached ONLY by one pull request from trunk that the owner merges himself
13
+ * (`colab deliver`). No colab command may move that branch — `refuseMove()` is the one guard every
14
+ * branch-moving push site asks.
15
+ *
16
+ * The key is `owner:`, not `upstream:`: "upstream" already names a different thing in CONVENTIONS
17
+ * §8 (a consumer filing a changed convention meaning back to the handbook) and, in git, a branch's
18
+ * tracking ref. A third meaning of the same word would be read wrong by somebody.
19
+ *
20
+ * Everything here is pure: the CLI does the git/gh reads and hands the results in.
21
+ */
22
+
23
+ const RESERVED = new Set(['trunk']);
24
+
25
+ /**
26
+ * Read the block. Absent → `{ declared: false }` (and every caller behaves exactly as before the
27
+ * key existed). Present → `{ declared: true, branch, remote, problems[] }`; a non-empty `problems`
28
+ * means the block is malformed and callers must fail closed.
29
+ */
30
+ function read(doc) {
31
+ if (!doc || !Object.prototype.hasOwnProperty.call(doc, 'owner') || doc.owner === null || doc.owner === undefined) {
32
+ return { declared: false, branch: null, remote: null, problems: [] };
33
+ }
34
+ const raw = doc.owner;
35
+ const problems = [];
36
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
37
+ problems.push(`owner must be a block with "branch:" (and optionally "remote:"), found ${JSON.stringify(raw)}`);
38
+ return { declared: true, branch: null, remote: null, problems };
39
+ }
40
+ for (const k of Object.keys(raw)) {
41
+ if (k !== 'branch' && k !== 'remote') problems.push(`owner has an unknown key "${k}" — only "branch" and "remote" are defined`);
42
+ }
43
+ const branch = raw.branch === null || raw.branch === undefined ? '' : String(raw.branch).trim();
44
+ const remote = raw.remote === null || raw.remote === undefined ? null : String(raw.remote).trim() || null;
45
+ if (!branch) problems.push('owner is declared without "branch:" — name the owner\'s branch the delivery PR targets');
46
+ else if (RESERVED.has(branch)) problems.push('owner.branch is "trunk" — "trunk" is a role, never a branch name (CONVENTIONS.md §2)');
47
+ return { declared: true, branch: branch || null, remote, problems };
48
+ }
49
+
50
+ /**
51
+ * Descriptor-level findings for the audit: the block's own shape, plus the collisions that would
52
+ * let a colab command reach the owner's branch — it may not BE trunk, an integration line, or the
53
+ * releaseBranch. Returns `[{ level: 'fail'|'warn', text }]`.
54
+ */
55
+ function evaluate(doc, { trunk, integration = [], releaseBranch = '', branches = null } = {}) {
56
+ const o = read(doc);
57
+ if (!o.declared) return [];
58
+ const out = o.problems.map((text) => ({ level: 'fail', text }));
59
+ if (!o.branch) return out;
60
+ if (trunk && o.branch === trunk) {
61
+ out.push({ level: 'fail', text: `owner.branch is the trunk ("${o.branch}") — trunk is the fleet's integration branch that \`colab ship\` merges into; the owner's branch must be a different one, reached only by \`colab deliver\`'s pull request` });
62
+ }
63
+ if ((integration || []).includes(o.branch)) {
64
+ out.push({ level: 'fail', text: `owner.branch "${o.branch}" is also listed in integration: — a session could then be cut from and shipped into the owner's branch` });
65
+ }
66
+ if (releaseBranch && releaseBranch === o.branch) {
67
+ out.push({ level: 'fail', text: `owner.branch "${o.branch}" is also the releaseBranch — a release would then fast-forward the owner's branch` });
68
+ }
69
+ if (Array.isArray(branches) && !branches.includes(o.branch)) {
70
+ out.push({ level: 'warn', text: `owner.branch "${o.branch}" is not among the branches this audit could list — check the name (it lives on the owner's remote)` });
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * The guard. `null` when a push to `branch` is allowed as far as this key is concerned; otherwise
77
+ * the refusal line. Fails closed on a malformed block: a descriptor that says "there is an owner's
78
+ * branch" but not legibly which one may not be pushed to at all — every refusal names why.
79
+ */
80
+ function refuseMove(doc, branch) {
81
+ const o = read(doc);
82
+ if (!o.declared) return null;
83
+ if (o.problems.length) {
84
+ return `project.yml owner: is malformed (${o.problems[0]}) — refusing to move any shared branch until it is fixed`;
85
+ }
86
+ if (branch && o.branch === String(branch)) {
87
+ return `"${branch}" is the owner's branch (project.yml owner.branch) — no colab command moves it. Deliver with \`colab deliver\`, which opens a pull request the owner merges himself.`;
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /**
93
+ * Classify the delivery PRs (head = trunk, base = owner.branch, any state), newest first by number.
94
+ * `prs` is `gh pr list --state all --json number,url,state,mergedAt,headRefOid,closedAt,title`.
95
+ *
96
+ * Returns `{ open, lastMerged, lastClosed, latest }` where `lastClosed` is the newest PR closed
97
+ * WITHOUT merge that is newer than `lastMerged` — the owner's rejection of the current batch.
98
+ * A merge is read from PR state (`state: MERGED` or a `mergedAt`), never from ancestry: the owner
99
+ * may squash or rebase, and then no trunk commit is an ancestor of his branch.
100
+ */
101
+ function classifyPrs(prs) {
102
+ const list = (Array.isArray(prs) ? prs : [])
103
+ .filter((p) => p && Number.isFinite(Number(p.number)))
104
+ .slice()
105
+ .sort((a, b) => Number(b.number) - Number(a.number));
106
+ const isMerged = (p) => String(p.state || '').toUpperCase() === 'MERGED' || !!p.mergedAt;
107
+ const isOpen = (p) => String(p.state || '').toUpperCase() === 'OPEN';
108
+ const open = list.find(isOpen) || null;
109
+ const lastMerged = list.find(isMerged) || null;
110
+ const lastClosed = list.find((p) => !isOpen(p) && !isMerged(p)
111
+ && (!lastMerged || Number(p.number) > Number(lastMerged.number))) || null;
112
+ return { open, lastMerged, lastClosed, latest: list[0] || null };
113
+ }
114
+
115
+ /**
116
+ * `#N` references in commit messages, in first-seen order, de-duplicated. Reads what `colab ship`
117
+ * writes (`Closes #N`, `Refs #N`, a trailing `(#N)`); an `owner/name#N` cross-repo reference is
118
+ * skipped — it names another tracker.
119
+ */
120
+ function issueRefs(messages) {
121
+ const seen = new Set();
122
+ const out = [];
123
+ for (const m of messages || []) {
124
+ const re = /(^|[^\w/.-])#(\d+)\b/g;
125
+ let x;
126
+ while ((x = re.exec(String(m))) !== null) {
127
+ const n = Number(x[2]);
128
+ if (!seen.has(n)) { seen.add(n); out.push(n); }
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /**
135
+ * Decide what `colab deliver` does, from the reads. Inputs:
136
+ * pending — `[{ sha, subject, body }]` trunk commits not yet delivered (oldest first)
137
+ * prs — classifyPrs() output
138
+ * headSha — trunk's tip on the remote
139
+ * reopen — `--reopen` given
140
+ * Returns `{ state, action, detail }`:
141
+ * state : 'nothing-to-deliver' | 'waiting-on-owner' | 'rejected' | 'ready'
142
+ * action : 'none' | 'refresh' | 'create'
143
+ * Pure and exhaustive — every combination lands on exactly one row, tested.
144
+ */
145
+ function decide({ pending, prs, headSha, reopen = false }) {
146
+ const n = (pending || []).length;
147
+ if (prs.open) {
148
+ return { state: 'waiting-on-owner', action: n ? 'refresh' : 'none',
149
+ detail: `PR #${prs.open.number} is open, waiting on the owner to merge it${n ? ` — ${n} commit(s) on it` : ''}` };
150
+ }
151
+ if (!n) {
152
+ return { state: 'nothing-to-deliver', action: 'none',
153
+ detail: prs.lastMerged ? `everything up to PR #${prs.lastMerged.number} is delivered; nothing new on trunk since` : 'trunk has nothing the owner\'s branch lacks' };
154
+ }
155
+ if (prs.lastClosed && !reopen) {
156
+ const same = headSha && prs.lastClosed.headRefOid && prs.lastClosed.headRefOid === headSha;
157
+ return { state: 'rejected', action: 'none',
158
+ detail: `PR #${prs.lastClosed.number} was closed without a merge${same ? ' at this same trunk tip' : ''} — the owner declined it. `
159
+ + 'Nothing opened. Read his reason on the PR; re-run with --reopen to offer the batch again.' };
160
+ }
161
+ return { state: 'ready', action: 'create', detail: `${n} commit(s) on trunk not yet delivered` };
162
+ }
163
+
164
+ /** Title and body of the delivery PR. No closing keywords: the issues already closed on trunk. */
165
+ function prText({ trunk, ownerBranch, pending, lastMerged }) {
166
+ const issues = issueRefs((pending || []).map((c) => `${c.subject}\n${c.body || ''}`));
167
+ const title = `Deliver ${trunk} → ${ownerBranch}: ${pending.length} change(s)${issues.length ? ` (${issues.map((i) => '#' + i).join(', ')})` : ''}`;
168
+ const lines = [
169
+ `This pull request carries work already landed on \`${trunk}\`, the integration branch, to \`${ownerBranch}\`.`,
170
+ 'It is opened by `colab deliver`, which never merges it: merging is yours, by any method (merge commit, squash or rebase).',
171
+ '',
172
+ `## Changes (${pending.length})`,
173
+ ...pending.map((c) => `- \`${String(c.sha).slice(0, 7)}\` ${c.subject}`),
174
+ ];
175
+ if (issues.length) {
176
+ lines.push('', '## Issues carried', ...issues.map((i) => `- #${i}`));
177
+ }
178
+ if (lastMerged) lines.push('', `Previous delivery: #${lastMerged.number}.`);
179
+ return { title, body: lines.join('\n') + '\n' };
180
+ }
181
+
182
+ module.exports = { read, evaluate, refuseMove, classifyPrs, issueRefs, decide, prText };