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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +309 -3
  3. package/README.vi.md +279 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +117 -0
  22. package/templates/release-auto.yml +470 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13746 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +259 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify.js +188 -0
  63. package/tools/lib/npm-publish-guard.js +242 -0
  64. package/tools/lib/orphan-worktree.js +127 -0
  65. package/tools/lib/owner-branch.js +182 -0
  66. package/tools/lib/place.js +782 -0
  67. package/tools/lib/ports.js +167 -0
  68. package/tools/lib/procs.js +185 -0
  69. package/tools/lib/readiness.js +240 -0
  70. package/tools/lib/records.js +185 -0
  71. package/tools/lib/refs-brake.js +95 -0
  72. package/tools/lib/release-cut.js +822 -0
  73. package/tools/lib/release-finalize.js +481 -0
  74. package/tools/lib/release-policy.js +358 -0
  75. package/tools/lib/release-tag.js +225 -0
  76. package/tools/lib/ship-batch.js +277 -0
  77. package/tools/lib/ship-roles.js +71 -0
  78. package/tools/lib/ship-target-sync.js +181 -0
  79. package/tools/lib/shipguard.js +317 -0
  80. package/tools/lib/shipped-branch.js +56 -0
  81. package/tools/lib/solo.js +213 -0
  82. package/tools/lib/squash.js +515 -0
  83. package/tools/lib/stale-base.js +70 -0
  84. package/tools/lib/stamp.js +703 -0
  85. package/tools/lib/state.js +262 -0
  86. package/tools/lib/teardown.js +83 -0
  87. package/tools/lib/trust-humans.js +104 -0
  88. package/tools/lib/util.js +98 -0
  89. package/tools/lib/wake.js +188 -0
  90. package/tools/lib/workflow-triggers.js +273 -0
  91. package/tools/lib/writes-authority.js +237 -0
  92. package/tools/lib/yaml.js +101 -0
  93. package/bin/cli.js +0 -3
@@ -0,0 +1,317 @@
1
+ 'use strict';
2
+ /**
3
+ * The three guards `colab ship` runs over what it is ABOUT to write into an immutable commit
4
+ * message, plus the one that decides a zero-commit branch's completion path. All pure: they take
5
+ * facts already read from git/gh and return findings. Git I/O stays in the CLI, same split as
6
+ * lib/squash.js — and for the same reason, which that module states plainly: `tools/colab` has no
7
+ * test harness, `tools/lib/*.test.js` is wired into CI, and every bug these functions exist to stop
8
+ * was invisible precisely because nothing tested it.
9
+ *
10
+ * WHY ALL THREE LIVE TOGETHER. They are one composition path — the harvest that decides `Closes
11
+ * #N`, the message that describes it, and the close that follows — and they were filed as three
12
+ * issues (#87, #88, #90) only because they were measured on three different days. Splitting them
13
+ * across modules would hide that a change to one can invalidate the others.
14
+ *
15
+ * THE SHARED CONSTRAINT, which is why these are gates and not advice: a squash message cannot be
16
+ * corrected without a force-push that rewrites published history and any tag pointing at it, and a
17
+ * `Closes #N` GitHub has honoured cannot be un-honoured — reopening leaves the false claim in the
18
+ * commit. Check before the merge, not after.
19
+ *
20
+ * A FOURTH GUARD, added for #119: `closesCoverage` re-reads the FINAL message — the exact string
21
+ * about to be handed to `git commit -m` — and asserts every issue this ship resolved to CLOSE has a
22
+ * `Closes #N` line in it. Investigation for #119 found both message paths (`--message` override and
23
+ * the composed path) already funnel through `lib/squash.js`'s `spliceCloses`, which guarantees this
24
+ * on every reachable path today — so the hard gate here is regression-proofing against a future
25
+ * path that composes a message some other way, not a fix for a currently-reachable failure. The
26
+ * genuinely reachable incident #119 describes (a branch's own `Closes #N`, written in a commit body
27
+ * that the squash does not carry verbatim, silently dropped) is caught by this same function as an
28
+ * ADVISORY finding (`dropped`), not a hard failure — see the doc comment on `closesCoverage`.
29
+ */
30
+
31
+ const squash = require('./squash.js');
32
+
33
+ // Issue numbers a branch NAME claims (CONVENTIONS.md §4: one trailing run). Defined in
34
+ // lib/branch-name.js since #348 — the one module that knows both branch shapes — and re-exported
35
+ // here so every existing caller keeps its import.
36
+ const branchNameLib = require('./branch-name.js');
37
+ const { branchIssueNumbers } = branchNameLib;
38
+
39
+ /** Every `#N` mentioned in any commit subject or body on the branch, de-duplicated. */
40
+ function commitIssueNumbers(commits) {
41
+ const out = new Set();
42
+ for (const c of Array.isArray(commits) ? commits : []) {
43
+ const text = `${(c && c.subject) || ''}\n${(c && c.body) || ''}`;
44
+ for (const m of text.matchAll(/#(\d+)\b/g)) out.add(Number(m[1]));
45
+ }
46
+ return [...out];
47
+ }
48
+
49
+ /**
50
+ * B1b's cross-check, performed by the tool instead of by whoever is reading (#87).
51
+ *
52
+ * `ship` resolves what it will close from the CLAIM REGISTRY, read at ship time. A claim written by
53
+ * a different, still-running session onto the same branch is indistinguishable from one the
54
+ * shipping session made itself — so a co-tenant joining a `group:` branch silently enlarges what
55
+ * the ship closes. Measured: a branch carrying #71 and #76 reported `issues: [71, 74, 76]`, because
56
+ * a second session claimed #74 onto the same worktree minutes after the ship was authorised and had
57
+ * only just started work. Nothing on the branch implemented #74. Had it proceeded, `Closes #74`
58
+ * would have gone into trunk's history and GitHub would have closed an issue whose work had not
59
+ * begun.
60
+ *
61
+ * CLAUDE.md's B1b already prescribed the fix in prose — git and the registry "fail in opposite
62
+ * directions… a number in one set and not the other is a finding" — and it was performed by hand.
63
+ * This is that same comparison, mechanical.
64
+ *
65
+ * `issues` is the registry's contribution; the branch NAME and the COMMIT BODIES are the two
66
+ * git-side sources §4 makes load-bearing. An issue corroborated by neither is the finding.
67
+ *
68
+ * Deliberately NOT downgraded to `Refs #N` here: `--refs` already exists for the case an operator
69
+ * means, and silently turning a suspicious Closes into a quiet Refs would hide the co-tenant
70
+ * collision that is the actual news.
71
+ */
72
+ function corroborateIssues(issues, branchName, commits) {
73
+ const fromName = new Set(branchIssueNumbers(branchName));
74
+ const fromCommits = new Set(commitIssueNumbers(commits));
75
+ const corroborated = [];
76
+ const uncorroborated = [];
77
+ for (const n of Array.isArray(issues) ? issues : []) {
78
+ const inName = fromName.has(n);
79
+ const inCommits = fromCommits.has(n);
80
+ if (inName || inCommits) corroborated.push({ issue: n, via: inName ? (inCommits ? 'branch name + commits' : 'branch name') : 'commit body' });
81
+ else uncorroborated.push({ issue: n });
82
+ }
83
+ return { corroborated, uncorroborated, ok: uncorroborated.length === 0 };
84
+ }
85
+
86
+ /**
87
+ * A Conventional Commit type prefix on a BRANCH name (`fix/ship-close-path-87` → `fix`), or null.
88
+ * Both §4 shapes (#348): `ada/box-a/fix/x-87` → `fix`, never the login. A name conforming to
89
+ * neither keeps the old read — its first `/`-segment — so grandfathered names behave as before.
90
+ */
91
+ function branchType(branchName) {
92
+ const p = branchNameLib.parse(branchName);
93
+ if (p) return p.type;
94
+ const m = /^([a-z]+)\//.exec(String(branchName || ''));
95
+ return m ? m[1] : null;
96
+ }
97
+
98
+ /**
99
+ * Does the subject the walk chose actually describe the unit being shipped (#88, Case 1)?
100
+ *
101
+ * The measured failure: a branch shipping a readiness gate and a whole design-artifact convention
102
+ * (+104 lines of CONVENTIONS.md) landed titled `fix(labels): correct mechanical-readiness tests…`
103
+ * — a test correction made incidental to a trunk sync. Release notes group on the Conventional
104
+ * Commit prefix, so a feature filed under `fix:`; and the one line a reader ever sees for that unit
105
+ * describes none of the work. The contributing cause is in lib/squash.js: the only commit that DID
106
+ * describe the deliverable carried `wip:`, which is ineligible to become the subject, so the walk
107
+ * landed on whatever housekeeping commit happened to be last.
108
+ *
109
+ * Two independent signals, both mechanical, neither blocking on its own — the operator is told
110
+ * before the irreversible step and can pass `--message`:
111
+ *
112
+ * - `type-mismatch`: the chosen subject's type disagrees with the branch's own type prefix. A
113
+ * `feat/` branch shipping under `fix:` is either a mis-titled squash or a mis-named branch, and
114
+ * both are worth a look before the message is immutable.
115
+ * - `narrow-subject`: the chosen commit touches a small fraction of the files the branch changed.
116
+ * This is the shape that catches Case 1 even when the types happen to agree — the subject is
117
+ * borrowed from a commit that did almost none of the work.
118
+ *
119
+ * `chosenFiles`/`branchFiles` are file-path arrays the caller read from git. A branch of one commit
120
+ * is exempt from `narrow-subject` by construction: that commit IS the branch.
121
+ */
122
+ function subjectSanity({ subject, branchName, chosenFiles, branchFiles, commitCount, parseSubject }) {
123
+ const findings = [];
124
+ const parsed = typeof parseSubject === 'function' ? parseSubject(subject) : null;
125
+ const bType = branchType(branchName);
126
+ if (parsed && bType && parsed.type !== bType) {
127
+ findings.push({
128
+ kind: 'type-mismatch',
129
+ detail: `subject is "${parsed.type}:" but the branch is "${bType}/" — the changelog will file this unit under ${parsed.type}`,
130
+ });
131
+ }
132
+ const chosen = Array.isArray(chosenFiles) ? chosenFiles.length : 0;
133
+ const total = Array.isArray(branchFiles) ? branchFiles.length : 0;
134
+ if (commitCount > 1 && total > 0 && chosen > 0 && chosen * 3 < total) {
135
+ findings.push({
136
+ kind: 'narrow-subject',
137
+ detail: `the commit titling this squash touches ${chosen} of the ${total} files the branch changed — it is unlikely to describe the deliverable`,
138
+ });
139
+ }
140
+ return findings;
141
+ }
142
+
143
+ /**
144
+ * Bare 40/7-hex shas asserted inside a message body (#88, Case 2).
145
+ *
146
+ * Measured: a squash body carried "…#71/#76 already landed in a825aad on this shared branch and are
147
+ * not touched here". `a825aad` was only ever a commit ON THAT BRANCH — the first ship attempt had
148
+ * been deferred, so all three issues in fact landed together in that very squash. The statement was
149
+ * true of the session's local view when it was written and false by the time it merged. The
150
+ * machine-generated `Closes` line directly above it was correct, so nothing broke; the two lines
151
+ * now contradict each other inside an immutable commit message, and the wrong one is the prose a
152
+ * human reads.
153
+ *
154
+ * The caller checks each returned sha with `git merge-base --is-ancestor <sha> <target>`. Only bare
155
+ * hex words are returned: a `#N` issue reference is not a sha, and a sha inside a URL belongs to
156
+ * whatever it links to, not to this repo's history.
157
+ */
158
+ function bodyShaClaims(message) {
159
+ const out = new Set();
160
+ for (const line of String(message || '').split('\n')) {
161
+ if (/^\s*(?:Co-authored-by|Signed-off-by|Claude-Session|Reviewed-by):/i.test(line)) continue;
162
+ for (const m of line.matchAll(/(?<![\w/#-])([0-9a-f]{7,40})(?![\w/-])/g)) {
163
+ const sha = m[1];
164
+ if (/^\d+$/.test(sha)) continue; // an all-digit run is a number in prose, not a sha
165
+ out.add(sha);
166
+ }
167
+ }
168
+ return [...out];
169
+ }
170
+
171
+ /**
172
+ * Does this issue carry evidence of a delivery that produced no diff (#90)?
173
+ *
174
+ * The gate on evidence-close mode. A session can finish with a real deliverable and ZERO commits —
175
+ * a decision recorded on its issue, an investigation concluding "no change needed", a design
176
+ * artifact stored outside the repo. Today `ship` refuses such a branch at B1 and no skill path ever
177
+ * closes the issue, so the claim is released, the worktree torn down, and the issue stays open
178
+ * forever. The fleet owner's ruling: an agent may perform the close WHEN the issue carries an
179
+ * evidence comment describing what was delivered.
180
+ *
181
+ * "Evidence" is deliberately defined as *a comment the tool did not write itself*. The coordinator
182
+ * bookkeeping markers (colab's 🔒 Claimed / ✅ Released / 🚢 Shipped / 🔖 Referenced, and the
183
+ * skills' ↩️ Sent back — #409: a coordinator asking the implementer to wrap its own work records
184
+ * that nothing was delivered yet, never that something was) are bookkeeping — an issue holding
185
+ * only those has had a session attached and nothing recorded, which is precisely the state that must
186
+ * NOT auto-close. Anything else is a human or an agent having written down what happened, which is
187
+ * the whole standard being asked for.
188
+ *
189
+ * The zero-diff fact itself is measured from git by the caller, never declared by the session — so
190
+ * an issue that carries no delivery-type label is still covered.
191
+ */
192
+ const TOOL_MARKS = ['🔒 Claimed', '✅ Released', '🚢 Shipped', '🔖 Referenced', '↩️ Sent back'];
193
+ function evidenceComments(comments) {
194
+ return (Array.isArray(comments) ? comments : []).filter((c) => {
195
+ const body = String((c && c.body) || '').trim();
196
+ if (!body) return false;
197
+ return !TOOL_MARKS.some((mark) => body.startsWith(mark));
198
+ });
199
+ }
200
+
201
+ /** True when the issue holds at least one comment colab did not write. */
202
+ function hasEvidence(comments) {
203
+ return evidenceComments(comments).length > 0;
204
+ }
205
+
206
+ /**
207
+ * The #119 gate: does the FINAL squash message — exactly the string about to be passed to
208
+ * `git commit -m` — carry a `Closes #N` for every issue this ship resolved to close?
209
+ *
210
+ * Uses `squash.closedIssueNumbers`, the SAME recogniser `spliceCloses` uses to decide what still
211
+ * needs adding, deliberately — a second, independently-written regex here is exactly the drift that
212
+ * would let this guard and the composer disagree about a message they are both looking at.
213
+ *
214
+ * Three findings, two different severities (see the module header for why they split this way):
215
+ *
216
+ * - `missing`: a number in `closeIssues` with no `Closes #N` in `message`. HARD FAILURE — this is
217
+ * ship's own resolved intent contradicting the text it is about to commit, with no inference
218
+ * involved. Investigation for #119 found no path today that reaches this (both `--message` and
219
+ * the composed path already run through `spliceCloses`, which guarantees it) — so this is
220
+ * regression-proofing a future composer bypass, not a fix for a reachable bug.
221
+ * - `dropped`: a number some commit's own text closes, that is in none of `closeIssues`,
222
+ * `refsIssues`, or `message` — the genuinely reachable #119 incident: a branch's own `Closes #N`
223
+ * lived in a commit body the squash did not carry verbatim (only the CHOSEN commit's body
224
+ * survives; others contribute only their subject as a bullet), and the number was never in the
225
+ * claim registry to begin with. ADVISORY — inferred from prose, which can be a mention of
226
+ * another repo's issue, a revert note, or a deliberate `--refs` decision the operator already
227
+ * made; not authoritative enough to block.
228
+ * - `stray`: a number `message` closes that is NOT in `closeIssues` — the mirror image. Tagged
229
+ * `refs` when the operator explicitly kept it open (`refsIssues`, the settled case
230
+ * `squash.js:176`/`reconcileClosesRefsConflict` documents: GitHub still honours an inherited
231
+ * `Closes #N` even when a `Refs #N` sits beside it, and this is deliberately NOT rewritten —
232
+ * ship already warns after the push), `not-carried` otherwise. ADVISORY for the same reason
233
+ * `dropped` is: rejecting a hand-written `Closes` here would overturn that settled rule, not add
234
+ * to it.
235
+ *
236
+ * @param {string} o.message the FINAL message, exactly as passed to `git commit -m`
237
+ * @param {Array<number|string>} o.closeIssues what ship resolved to CLOSE
238
+ * @param {Array<number|string>} [o.refsIssues] what ship resolved to keep open
239
+ * @param {Array<{subject,body}>} [o.commits] branchCommits() output — feeds `dropped` only
240
+ * @returns {{ok:boolean, missing:number[], dropped:number[],
241
+ * stray: Array<{issue:number, reason:'refs'|'not-carried'}>}}
242
+ */
243
+ function closesCoverage({ message, closeIssues, refsIssues = [], commits = [] }) {
244
+ const closed = new Set(squash.closedIssueNumbers(message).map(Number));
245
+ const closeSet = new Set((Array.isArray(closeIssues) ? closeIssues : []).map(Number));
246
+ const refsSet = new Set((Array.isArray(refsIssues) ? refsIssues : []).map(Number));
247
+
248
+ const missing = [...closeSet].filter((n) => !closed.has(n));
249
+
250
+ const fromCommits = new Set();
251
+ for (const c of Array.isArray(commits) ? commits : []) {
252
+ const text = `${(c && c.subject) || ''}\n${(c && c.body) || ''}`;
253
+ for (const n of squash.closedIssueNumbers(text)) fromCommits.add(Number(n));
254
+ }
255
+ const dropped = [...fromCommits].filter((n) => !closeSet.has(n) && !refsSet.has(n) && !closed.has(n));
256
+
257
+ const stray = [...closed]
258
+ .filter((n) => !closeSet.has(n))
259
+ .map((n) => ({ issue: n, reason: refsSet.has(n) ? 'refs' : 'not-carried' }));
260
+
261
+ return { ok: missing.length === 0, missing, dropped, stray };
262
+ }
263
+
264
+ /**
265
+ * #153: what a ZERO-claim resolution means, and whether ship should warn or refuse.
266
+ *
267
+ * A branch can resolve to zero claimed issues for two structurally different reasons, and only one
268
+ * of them is safe to warn-and-continue on:
269
+ *
270
+ * - the branch never claimed to close anything (no trailing issue-number group in its name) — a
271
+ * chore, a doc fix, a deliberate zero-diff evidence-close. Warn; nothing contradicts it.
272
+ * - the branch NAME says it carries issues, but the local claim registry has nothing for them.
273
+ * That contradiction is the shape measured in #153: a sweep run on a machine that does not hold
274
+ * the claim (claims are written to both local state and GitHub, but ship's issue resolution used
275
+ * to read only the local registry) reported "(none claimed)", every precondition passed, and the
276
+ * branch would have merged with no `Closes #N` — leaving the issues open with their code already
277
+ * on trunk. Ruling (2026-08-08, option B): refuse here, because the branch's own name is evidence
278
+ * the registry is the one that's wrong, not the work.
279
+ *
280
+ * `brokenClaimsCount` is evaluated FIRST and independently: a claim that already names a branch which
281
+ * resolves to no ref is a stronger, pre-existing signal (the registry itself is provably broken, #53)
282
+ * and refuses regardless of what the branch name says — that behavior predates this function and is
283
+ * unchanged by it.
284
+ *
285
+ * Callers with issuesCount > 0 should not call this at all — `relevant: false` says so defensively,
286
+ * so a caller that does anyway gets an inert verdict rather than a silently wrong one.
287
+ *
288
+ * #324: the legit zero had a hole on any fleet where more than one machine ships. A branch that
289
+ * exists ONLY as origin's copy (`remoteOnly` — no local ref; ship's B0 would check it out from the
290
+ * remote) with no digit suffix and no local claim read as a chore, so ship landed another machine's
291
+ * in-flight work under this session with nothing closed and nothing released — and `chore/bump-node`
292
+ * or `fix/parser-rewrite` are ordinary names. That shape now refuses (`remote-only-unclaimed`) unless
293
+ * the caller passes `adopt` explicitly (`adopted` — the caller records the adoption). `adopt` never
294
+ * bypasses the two refusals above it: a broken registry and a branch naming issues each have their
295
+ * own remedy (repair; claim), and adopting past them would ship with no `Closes #N` exactly as #153
296
+ * forbids. A LOCAL digit-less unclaimed branch is still a legit zero — this machine made it.
297
+ * The fourth argument is optional; a three-argument call behaves exactly as before.
298
+ */
299
+ function zeroClaimVerdict(issuesCount, branchName, brokenClaimsCount, { remoteOnly = false, adopt = false } = {}) {
300
+ if (issuesCount > 0) return { relevant: false, ok: true, refuse: false, reason: null };
301
+ if (brokenClaimsCount > 0) {
302
+ return { relevant: true, ok: false, refuse: true, reason: 'broken-claims' };
303
+ }
304
+ const named = branchIssueNumbers(branchName);
305
+ if (named.length > 0) {
306
+ return { relevant: true, ok: false, refuse: true, reason: 'branch-names-issues', named };
307
+ }
308
+ if (remoteOnly && !adopt) return { relevant: true, ok: false, refuse: true, reason: 'remote-only-unclaimed' };
309
+ if (remoteOnly && adopt) return { relevant: true, ok: true, refuse: false, reason: 'adopted' };
310
+ return { relevant: true, ok: true, refuse: false, reason: 'legit-zero' };
311
+ }
312
+
313
+ module.exports = {
314
+ branchIssueNumbers, commitIssueNumbers, corroborateIssues, branchType,
315
+ subjectSanity, bodyShaClaims, evidenceComments, hasEvidence, TOOL_MARKS,
316
+ closesCoverage, zeroClaimVerdict,
317
+ };
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ /**
3
+ * What `colab ship` B3 does with the branch whose content has just landed (#17, #368).
4
+ *
5
+ * THE DEFAULT IS TO KEEP IT (#17) — with ONE exception, #368: a ship that closes NOTHING and
6
+ * references at least one issue (`Refs #N` only — `--refs`, or the `tracking` label).
7
+ *
8
+ * Why the exception exists. A kept branch is harmless while every issue it names is closed: every
9
+ * name-keyed reader (triage's ref enumeration, `git branch -a --list '*<n>*'`, a scheduler's
10
+ * file-hold check) sees a closed number and moves on, and code-sweep lists it as `spent-remote`.
11
+ * A Refs-only ship breaks both halves of that at once. Its issue STAYS OPEN by design (a tracking
12
+ * issue, #48), so the ref reads as live work on that issue for as long as the issue lives — which,
13
+ * for a tracking issue, is indefinitely. A squash leaves no ancestry, so nothing can tell from the
14
+ * graph that it is spent. And the ship has just released the claim, so code-sweep's
15
+ * orphan-candidate bucket (which needs `in-progress`) never sees it either. Measured: one such ref
16
+ * held a file against a scheduler's start check for ~8 hours until a human deleted it by hand.
17
+ *
18
+ * Ship is the one moment anything knows FOR CERTAIN the ref is spent — the content was pushed to
19
+ * the target a few lines earlier — so that is where it goes. #17's reason for keeping (deleting
20
+ * refs from a shared remote unasked is irreversible, reporting is not) still holds for a Closes
21
+ * ship, whose kept ref reads as spent to every reader and costs nothing but clutter. It does not
22
+ * hold here: this ref's only remaining effect is to look live, and that effect is not harmless.
23
+ *
24
+ * `--keep-branch` restores the old behaviour for a Refs-only ship (e.g. a follow-up slice will be
25
+ * cut from the same branch). `--delete-branch` still forces deletion for any ship. Passing both is
26
+ * a contradiction the caller must resolve — see `conflictingFlags`.
27
+ *
28
+ * Pure: no git, no I/O. `handleShippedBranch` in tools/colab performs what this decides.
29
+ *
30
+ * @param {{ closeIssues?: number[], refsIssues?: number[], deleteBranch?: boolean, keepBranch?: boolean }} o
31
+ * @returns {{ delete: boolean, reason: 'flag-delete'|'flag-keep'|'refs-only'|'default', detail: string, refs?: number[] }}
32
+ * `refs` is present on `refs-only` only: the still-open issues the kept ref would have named.
33
+ */
34
+ function shippedBranchDisposition({ closeIssues = [], refsIssues = [], deleteBranch = false, keepBranch = false } = {}) {
35
+ if (deleteBranch) return { delete: true, reason: 'flag-delete', detail: '--delete-branch' };
36
+ const refsOnly = closeIssues.length === 0 && refsIssues.length > 0;
37
+ if (keepBranch) {
38
+ return { delete: false, reason: 'flag-keep', detail: refsOnly ? '--keep-branch (overrides the Refs-only delete, #368)' : '--keep-branch' };
39
+ }
40
+ if (refsOnly) {
41
+ return {
42
+ delete: true,
43
+ reason: 'refs-only',
44
+ refs: refsIssues.slice(),
45
+ detail: `Refs-only ship (${refsIssues.map((n) => `#${n}`).join(', ')} stays open) — a kept ref would read as live work on an open issue (#368); --keep-branch to keep it`,
46
+ };
47
+ }
48
+ return { delete: false, reason: 'default', detail: 'default; --delete-branch to remove it, or `colab doctor` to list what has accumulated' };
49
+ }
50
+
51
+ /** `--delete-branch` and `--keep-branch` together: refused, never silently resolved. */
52
+ function conflictingFlags({ deleteBranch = false, keepBranch = false } = {}) {
53
+ return !!(deleteBranch && keepBranch);
54
+ }
55
+
56
+ module.exports = { shippedBranchDisposition, conflictingFlags };
@@ -0,0 +1,213 @@
1
+ 'use strict';
2
+ /**
3
+ * Solo flow (CONVENTIONS.md, "Solo flow") — the entry/exit gate `colab solo` runs.
4
+ *
5
+ * Extracted from tools/colab so the gate is testable against a REAL git repo (same reason
6
+ * lib/landed.js is a module and not inline in the CLI): the whole point of this gate is "never
7
+ * an honor system", so its answer has to be measured against git's actual state, not a mock that
8
+ * agrees with whatever we believed when we wrote it.
9
+ *
10
+ * Pure with respect to state.json: every function here takes the loaded state object (or its
11
+ * relevant slice) as a parameter and returns a verdict; nothing in this module reads or writes
12
+ * ~/.colab/state.json itself — that stays tools/colab's job, same split as lib/readiness.js.
13
+ */
14
+
15
+ const git = require('./git');
16
+ const writesAuthority = require('./writes-authority.js');
17
+
18
+ // #237 (⚖ Decision on #233): `writes` stopped selecting a write-conflict prevention METHOD and
19
+ // became a two-state VETO — see writes-authority.js's header. `writesMode` and the old
20
+ // `soloEligibility` below (which keyed off `resolveWrites(...).value === 'serial-direct'`) are
21
+ // retired with it. Eligibility is now a SESSION-IDENTITY question — is a human at the keyboard,
22
+ // asserted with COLAB_HUMAN=1 — gated by the veto, not selected by a declared method.
23
+
24
+ /**
25
+ * Local branches carrying commits their upstream (or, absent one, `origin/<trunk>`) does not have.
26
+ * Returns `[{branch, reason}]` — empty means every local branch is fully pushed.
27
+ *
28
+ * Checked against ALL local branches, not just the current one: a forgotten feature branch sitting
29
+ * unpushed beside the trunk checkout is exactly the kind of "was somebody already partway into
30
+ * something here" fact solo flow's entry gate exists to catch, and it would be invisible to a check
31
+ * that only looked at HEAD.
32
+ */
33
+ function unpushedBranches(repoAbs, trunk, remote = git.remoteInfo(repoAbs).name || 'origin') {
34
+ const r = git.git(['for-each-ref', '--format=%(refname:short)', 'refs/heads/'], repoAbs);
35
+ if (!r.ok) return [];
36
+ const out = [];
37
+ for (const b of r.stdout.split('\n').map((s) => s.trim()).filter(Boolean)) {
38
+ const up = git.git(['rev-parse', '--abbrev-ref', '--symbolic-full-name', `${b}@{u}`], repoAbs);
39
+ const remoteRef = up.ok && up.stdout ? up.stdout : `${remote}/${trunk}`;
40
+ if (!git.git(['rev-parse', '--verify', '--quiet', remoteRef], repoAbs).ok) {
41
+ out.push({ branch: b, reason: `no upstream and no ${remoteRef} — never pushed` });
42
+ continue;
43
+ }
44
+ const ahead = git.git(['rev-list', '--count', `${remoteRef}..${b}`], repoAbs);
45
+ const n = ahead.ok ? (parseInt(ahead.stdout, 10) || 0) : 0;
46
+ if (n > 0) out.push({ branch: b, reason: `${n} commit(s) ahead of ${remoteRef}` });
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /**
52
+ * `git status --porcelain`, tracked AND untracked. Solo's "clean tree" is deliberately the
53
+ * stricter reading (lib/git.js's `dirtyTracked` ignores untracked cruft, which is right for a
54
+ * ship precondition but wrong here — solo flow's whole premise is "this checkout has nothing
55
+ * anyone else needs to know about", and an untracked file is exactly the kind of thing a returning
56
+ * session would otherwise have to notice by eye).
57
+ *
58
+ * #86: this is now a thin adapter over `git.dirtyAny` rather than its own porcelain call. It was
59
+ * written here first, which is how the repo ended up with two independent implementations of one
60
+ * reading — and only this copy counted untracked files, while the teardown gate that most needed
61
+ * them did not. Keeps the array shape solo's callers and tests expect.
62
+ */
63
+ function fullyDirty(repoAbs) {
64
+ const d = git.dirtyAny(repoAbs);
65
+ return d ? d.split('\n').filter(Boolean) : [];
66
+ }
67
+
68
+ /**
69
+ * Entry-gate problems for `colab solo` in `repoAbs`, given the already-loaded state and the repo's
70
+ * resolved trunk. Empty array = clear to open solo flow. Never throws; every check degrades to "no
71
+ * problem found" if git itself is unavailable, because a missing git is a bigger failure the CLI
72
+ * surfaces elsewhere, not a reason to silently claim the tree is dirty.
73
+ *
74
+ * Deliberately does NOT refuse merely because a worktree exists somewhere in this repo (#236), nor
75
+ * because a claim is held somewhere in this repo (#240) — the same category error, twice. The claim
76
+ * registry (lib/state.js `claims`) holds an *issue*, not a *place* (lib/place.js header): a claim
77
+ * tied to a worktree elsewhere is that worktree's business, not this checkout's, and a worktree is a
78
+ * different directory with a different checkout — a session writing there is not a writer of the
79
+ * checkout solo flow is about to commit straight to, and cannot become one. The resource this gate
80
+ * protects is `repoAbs`'s own checkout, not the repo as a whole: `cmdSolo` covers that
81
+ * checkout-scoped conflict separately, via `place.conflict` against a live place-claim held here
82
+ * (CONVENTIONS.md, "Solo flow", rule 1) — the thing a worktree or an off-checkout claim can never
83
+ * be. A claim taken directly against the trunk checkout (no worktree) already acquires that same
84
+ * place-claim at claim time (`cmdClaim`'s `takingPlace` path), so `place.conflict` catches it too;
85
+ * nothing here needs to re-check the claim registry to see it.
86
+ */
87
+ function entryProblems(st, repoAbs, trunk) {
88
+ const problems = [];
89
+
90
+ const cur = git.git(['branch', '--show-current'], repoAbs);
91
+ if (cur.ok && cur.stdout && cur.stdout !== trunk) {
92
+ problems.push(`checked out on "${cur.stdout}", not trunk "${trunk}" — solo commits go straight to trunk`);
93
+ }
94
+
95
+ for (const u of unpushedBranches(repoAbs, trunk)) problems.push(`unpushed branch "${u.branch}" (${u.reason})`);
96
+
97
+ const dirty = fullyDirty(repoAbs);
98
+ if (dirty.length) problems.push(`tree not clean (${dirty.length} path(s) — tracked or untracked)`);
99
+
100
+ return problems;
101
+ }
102
+
103
+ /**
104
+ * Exit-gate problems for `colab solo --done`: tree clean, and the checked-out branch fully pushed
105
+ * to `origin/<trunk>`. Deliberately narrower than the entry gate — `--done` is closing THIS
106
+ * checkout's work, not re-auditing every local branch in the repo.
107
+ */
108
+ function exitProblems(repoAbs, trunk, remote = git.remoteInfo(repoAbs).name || 'origin') {
109
+ const problems = [];
110
+
111
+ const dirty = fullyDirty(repoAbs);
112
+ if (dirty.length) problems.push(`tree not clean (${dirty.length} path(s)) — commit or discard first`);
113
+
114
+ const cur = git.git(['branch', '--show-current'], repoAbs);
115
+ const branchName = cur.ok && cur.stdout ? cur.stdout : trunk;
116
+ const upstreamRef = `${remote}/${trunk}`;
117
+ if (git.git(['rev-parse', '--verify', '--quiet', upstreamRef], repoAbs).ok) {
118
+ const ahead = git.git(['rev-list', '--count', `${upstreamRef}..${branchName}`], repoAbs);
119
+ const n = ahead.ok ? (parseInt(ahead.stdout, 10) || 0) : 0;
120
+ if (n > 0) problems.push(`${n} commit(s) not pushed to ${upstreamRef} — push before closing`);
121
+ }
122
+
123
+ return problems;
124
+ }
125
+
126
+ /**
127
+ * Is solo flow (trunk-direct) legal for this repo right now, and on what authority?
128
+ *
129
+ * #237 (⚖ Decision on #233): eligibility is a SESSION-IDENTITY question, gated by the veto —
130
+ * not a declared-method question. `writes: isolated` refuses outright, for a human exactly as
131
+ * for an automated session — no flag lowers that bar. Absence, and every other declared value
132
+ * (both `serial-*` spellings, the `serial` alias, anything unrecognised), permit trunk-direct
133
+ * to an ATTENDED session: `human` must be `true`, asserted by the CALLER from `COLAB_HUMAN=1`
134
+ * (transcribed on the human's explicit instruction, never inferred, and never from a headless,
135
+ * scheduled or driver session — CONVENTIONS.md §5, "The human flag").
136
+ *
137
+ * Deliberately does NOT read `process.env` itself — this module's header states every function
138
+ * here is pure with respect to external state, and that split is what lets a test drive both
139
+ * branches without mutating the ambient environment. The CLI (`tools/colab`'s `cmdSolo`) reads
140
+ * `COLAB_HUMAN` and passes the boolean in.
141
+ *
142
+ * `human` defaults to `false` so a caller that forgets the argument fails CLOSED (refused), not
143
+ * open. The veto is checked FIRST: a vetoed repo must never be told "re-run with COLAB_HUMAN=1"
144
+ * — that would advertise a route around a bar no flag may lower.
145
+ *
146
+ * Returns `{ok:true, via:'human'}` or `{ok:false, code, reason}` where `code` is `'veto'`
147
+ * (writes: isolated — no flag can change this) or `'not-human'` (set COLAB_HUMAN=1).
148
+ */
149
+ function soloEligibility(doc, { human = false } = {}) {
150
+ if (writesAuthority.trunkDirectVetoed(doc && doc.writes)) {
151
+ return {
152
+ ok: false,
153
+ code: 'veto',
154
+ reason: 'solo flow is refused here: this repo declares writes: isolated, which vetoes '
155
+ + 'trunk-direct for every session, human or not (CONVENTIONS.md, Writes). Use a '
156
+ + 'worktree and a branch.',
157
+ };
158
+ }
159
+ if (!human) {
160
+ return {
161
+ ok: false,
162
+ code: 'not-human',
163
+ reason: 'solo flow commits straight to trunk and requires a human at the keyboard: '
164
+ + 're-run with COLAB_HUMAN=1, set only on a human\'s explicit instruction — never '
165
+ + 'inferred, and never from a headless, scheduled or driver session. (No field, flag '
166
+ + 'or project.yml value can lower this bar.)',
167
+ };
168
+ }
169
+ return { ok: true, via: 'human' };
170
+ }
171
+
172
+ /**
173
+ * The two conditions from CONVENTIONS.md §2 ("Writes") that make a branch mandatory for an
174
+ * ATTENDED trunk-direct session (#237: every other kind of session has a branch by construction
175
+ * — a worktree — so this now governs solo flow specifically, not a declared `writes: serial`
176
+ * method), evaluated against state where it can be:
177
+ *
178
+ * 1. units-in-flight — more than one claim/worktree/place-claim already live on the repo.
179
+ * Machine-decidable from `st`, so `met` is a real boolean.
180
+ * 2. pre-merge-gate — something (CI, review) must inspect the unit before it lands. This is
181
+ * a DECLARED fact this module cannot see from git/state alone, so `met` is `null` — never
182
+ * `false`. Returning `false` here would read as "no gate exists", which this function is
183
+ * not positioned to claim.
184
+ *
185
+ * `mandatory` is `true` only when condition 1 is affirmatively met; a `null` condition 2 never
186
+ * flips `mandatory` to `true` on its own, because "cannot tell" must not read as "cannot apply".
187
+ */
188
+ function branchMandatory(st, repoAbs) {
189
+ const wts = Object.values((st && st.worktrees) || {}).filter((w) => w.repo === repoAbs).length;
190
+ const claims = Object.entries((st && st.claims) || {}).filter(([k]) => k.startsWith(`${repoAbs}#`)).length;
191
+ const places = Object.values((st && st.places) || {}).filter((p) => p.repo === repoAbs).length;
192
+ const unitsInFlight = wts + claims + places;
193
+ const unitsMet = unitsInFlight > 1;
194
+
195
+ const conditions = [
196
+ {
197
+ id: 'units-in-flight',
198
+ met: unitsMet,
199
+ why: unitsMet
200
+ ? `${unitsInFlight} units in flight on this repo (worktrees+claims+place-claims) — more than one writer`
201
+ : `${unitsInFlight} unit(s) in flight — a single writer needs no branch on this condition alone`,
202
+ },
203
+ {
204
+ id: 'pre-merge-gate',
205
+ met: null,
206
+ why: 'not machine-decidable — a repo declares whether a unit must be inspected before landing; this check cannot see that fact',
207
+ },
208
+ ];
209
+
210
+ return { mandatory: unitsMet, conditions };
211
+ }
212
+
213
+ module.exports = { unpushedBranches, fullyDirty, entryProblems, exitProblems, soloEligibility, branchMandatory };