@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,277 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/ship-batch.js — batch landing (#373): test up to N green candidates as ONE combined
4
+ * head, then fast-forward trunk.
5
+ *
6
+ * Landing is serial by construction without this: every merge moves trunk, so the next candidate
7
+ * pays a whole CI cycle for its post-sync re-run, and a queue of green work drains at one change
8
+ * per trunk run. Every mature system that lands several changes per cycle tests the COMBINED state
9
+ * before it becomes trunk (merge trains, merge queues, rollups) — none lands first and tests after.
10
+ * So: trunk head + one squash commit per member, pushed to `ship-batch/<trunk-sha7>`, one combined
11
+ * run, then a fast-forward only if trunk has not moved. Trunk only ever receives a state that
12
+ * passed CI as a whole.
13
+ *
14
+ * Pure: facts in, decisions out — no git, no gh, no clock. `tools/colab`'s `cmdShipBatch` does the
15
+ * I/O and asks this module every question whose answer is a rule. Same posture as ci-verdict.js.
16
+ *
17
+ * File-disjointness is a PRE-FILTER here (it lowers eviction odds), never the correctness gate:
18
+ * semantic conflicts need no shared file. The combined run is the gate.
19
+ */
20
+
21
+ const MAX_BATCH = 3;
22
+ const REF_PREFIX = 'ship-batch/';
23
+ // A concrete ref a `branches:` filter is tested against. Any 7-hex tail works: GitHub's filters see
24
+ // the literal ref name, and the question is only whether `ship-batch/**` (or a wider glob) admits it.
25
+ const PROBE_REF = `${REF_PREFIX}0000000`;
26
+ const TRAILER_KEY = 'Ship-Batch';
27
+
28
+ /**
29
+ * `ship-batch:` from project.yml. Absent → 1 (serial, today's behaviour). An integer 1..3 → that
30
+ * (a single-digit string reads the same). Anything else — 0, 4, 2.5, true, a word — FAILS CLOSED to
31
+ * serial, with the reason: a malformed opt-in must never widen what ship does. The audit fails the
32
+ * same values.
33
+ */
34
+ function parseShipBatch(doc) {
35
+ const has = !!doc && Object.prototype.hasOwnProperty.call(doc, 'ship-batch');
36
+ if (!has || doc['ship-batch'] === null || doc['ship-batch'] === undefined) {
37
+ return { n: 1, declared: false, valid: true, reason: 'ship-batch absent' };
38
+ }
39
+ const v = doc['ship-batch'];
40
+ // A digit string is accepted too: the audit's flat reader keeps every scalar a string, and the two
41
+ // readers must agree on what is valid — a value one accepts and the other refuses is drift.
42
+ const n = typeof v === 'number' ? v : (typeof v === 'string' && /^[1-9]$/.test(v.trim()) ? Number(v.trim()) : NaN);
43
+ if (Number.isInteger(n) && n >= 1 && n <= MAX_BATCH) {
44
+ return { n, declared: true, valid: true, reason: `ship-batch: ${n}` };
45
+ }
46
+ return { n: 1, declared: true, valid: false, reason: `ship-batch is ${JSON.stringify(v)}, expected an integer 1–${MAX_BATCH} (omit for serial)` };
47
+ }
48
+
49
+ function batchRefName(baseSha) {
50
+ return `${REF_PREFIX}${String(baseSha || '').slice(0, 7)}`;
51
+ }
52
+
53
+ /** `ship-batch/<hex7>` (with or without `refs/heads/`) → `{ ref, base7 }`, else null. */
54
+ function parseBatchRef(ref) {
55
+ const m = /^(?:refs\/heads\/)?(ship-batch\/([0-9a-f]{7}))$/.exec(String(ref || ''));
56
+ return m ? { ref: m[1], base7: m[2] } : null;
57
+ }
58
+
59
+ /**
60
+ * The trailer each batch commit carries. It is what lets a LATER `colab ship --batch` call rebuild
61
+ * the member list from the ref alone — no batch state is kept in ~/.colab. It names a branch (already
62
+ * pushed, so already public) and a sha, never a host.
63
+ */
64
+ function memberTrailer({ ref, branch, sha }) {
65
+ return `${TRAILER_KEY}: ${ref} ${branch}@${sha}`;
66
+ }
67
+
68
+ /** Every `Ship-Batch:` trailer across commit messages, in order → [{ ref, branch, sha }]. */
69
+ function parseMemberTrailers(messages) {
70
+ const out = [];
71
+ for (const msg of messages || []) {
72
+ for (const line of String(msg || '').split('\n')) {
73
+ const m = new RegExp(`^${TRAILER_KEY}:\\s+(\\S+)\\s+(\\S+)@([0-9a-f]{7,40})\\s*$`).exec(line.trim());
74
+ if (m) out.push({ ref: m[1], branch: m[2], sha: m[3] });
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * A member's OWN head CI, read as a joining class (§4 Branch CI):
82
+ * green every run at its head finished, all success
83
+ * none-cannot-arrive no run, and no workflow fires on a push to that branch — nothing to wait for;
84
+ * the combined run is the first CI the change sees, and it gates
85
+ * none-pending no run yet, but one could still arrive → not joinable yet
86
+ * pending a run is still in flight → not joinable yet
87
+ * red a run finished not-green → never joins; it goes back to its implementer
88
+ * `summary` is git.summarizeRunsForCommit's shape (null = the read failed → pending, never green).
89
+ */
90
+ function branchCiClass(summary, canArrive) {
91
+ if (!summary) return 'pending';
92
+ if (summary.status === 'none') return canArrive ? 'none-pending' : 'none-cannot-arrive';
93
+ if (summary.status !== 'completed') return 'pending';
94
+ return summary.conclusion === 'success' ? 'green' : 'red';
95
+ }
96
+
97
+ /**
98
+ * Can this member join a batch? `report` is its own `colab ship --dry --json` body (the SAME gates
99
+ * every serial ship meets — not a copy of them). Anything that makes the member special goes
100
+ * serial, where the special path already lives:
101
+ * - evidence-close / pr-pending (the #350 pause) — not a squash;
102
+ * - a target that is not trunk (an integration line);
103
+ * - the docs-only autonomy door (#345) — it is judged per branch, re-measured after B0's sync;
104
+ * - a migration, ci-grant or ci-cure — each is a per-member human door, never a batch one;
105
+ * - an adopted branch;
106
+ * - a member editing .github/workflows/** — it would change what grades the batch.
107
+ */
108
+ function memberEligibility(report, ciClass, { trunk, touchesWorkflows = false } = {}) {
109
+ const no = (why) => ({ ok: false, why });
110
+ if (!report) return no('its own ship precondition read failed');
111
+ if (!report.ok) {
112
+ const failed = (report.checks || []).filter((c) => !c.ok).map((c) => c.name);
113
+ return no(`its own ship preconditions fail (${failed.join(', ') || 'see colab ship --dry'})`);
114
+ }
115
+ if (report.mode !== 'squash') return no(`completion path is ${report.mode}, not a squash`);
116
+ if (report.target !== trunk) return no(`its base is "${report.target}", not ${trunk}`);
117
+ if (!report.autonomyGate || report.autonomyGate.via !== 'auto-trunk') {
118
+ return no('it lands through the docs-only door (#345), which is judged per branch');
119
+ }
120
+ // Any migration refuses, granted or not, whichever role granted it (#401) — the grant is a
121
+ // per-member door judged against ONE head, never a batch.
122
+ if (report.migrationGrant) return no('it carries migrations (granted or not) — a per-member door, never a batch');
123
+ if (report.ciGrant || report.ciCure) return no('trunk CI passes for it only through a grant/cure door — per member, never a batch');
124
+ if (report.coreReview && (report.coreReview.verdict === 'pending' || report.coreReview.verdict === 'approved')) {
125
+ return no('it touches a core path under review (#350)');
126
+ }
127
+ if ((report.checks || []).some((c) => /Colab-Adopted|adopted explicitly/.test(String(c.detail || '')))) {
128
+ return no('it is an adopted branch');
129
+ }
130
+ if (touchesWorkflows) return no('it edits .github/workflows/** — it would change what grades the batch');
131
+ if (ciClass === 'green' || ciClass === 'none-cannot-arrive') return { ok: true, why: `own head CI: ${ciClass}` };
132
+ if (ciClass === 'red') return no('red at its own head — it goes back to its implementer');
133
+ return no(`its own head CI has not finished (${ciClass}) — not joinable yet`);
134
+ }
135
+
136
+ /**
137
+ * Pick up to `n` from eligible candidates `[{ branch, files: [] }]`, in the order given. File-disjoint
138
+ * candidates are taken first; the rest fill any remaining slot in order. Only a pre-sort: a member
139
+ * sharing a file is still admitted when a slot is free — the build's merge and the combined run decide.
140
+ *
141
+ * `opts.isGenerated(path)` (#387): a path the repo regenerates rather than authors is not an overlap —
142
+ * the build regenerates it on the combined head, exactly as B0 does for one branch — so sharing only
143
+ * such paths leaves two candidates disjoint.
144
+ */
145
+ function selectMembers(candidates, n, opts = {}) {
146
+ const isGenerated = typeof opts.isGenerated === 'function' ? opts.isGenerated : () => false;
147
+ const list = Array.isArray(candidates) ? candidates : [];
148
+ const selected = [];
149
+ const used = new Set();
150
+ const seen = new Set();
151
+ for (const c of list) {
152
+ if (selected.length >= n) break;
153
+ const files = (c.files || []).filter((f) => !isGenerated(f));
154
+ if (files.some((f) => used.has(f))) continue;
155
+ selected.push(c); seen.add(c.branch);
156
+ for (const f of files) used.add(f);
157
+ }
158
+ for (const c of list) {
159
+ if (selected.length >= n) break;
160
+ if (seen.has(c.branch)) continue;
161
+ selected.push(c); seen.add(c.branch);
162
+ }
163
+ const overflow = list.filter((c) => !seen.has(c.branch));
164
+ return { selected, overflow };
165
+ }
166
+
167
+ /**
168
+ * Is the combined run wired at all? `fires` = the workflow files that fire on a push to PROBE_REF
169
+ * (workflow-triggers.js answers that). None → the combined run can never arrive, and ship must say
170
+ * so and go serial — never wait forever.
171
+ */
172
+ function wiring(fires) {
173
+ const list = Array.isArray(fires) ? fires : [];
174
+ return { wired: list.length > 0, fires: list };
175
+ }
176
+
177
+ /**
178
+ * The combined run's verdict from every run row at the batch head (`{status, conclusion, attempt,
179
+ * databaseId}`). Same all-runs rule as summarizeRunsForCommit: any finished not-green row (cancelled
180
+ * aside) makes it red; any unfinished row keeps it pending; green needs every row finished and at
181
+ * least one success. `attempt` is the highest run attempt seen — how many times it was re-run.
182
+ */
183
+ function combinedVerdict(rows) {
184
+ const list = Array.isArray(rows) ? rows : null;
185
+ if (list === null) return { state: 'pending', attempt: 1, runIds: [], why: 'the run list could not be read' };
186
+ const runIds = list.map((r) => r.databaseId).filter((x) => x !== null && x !== undefined);
187
+ const attempt = list.reduce((m, r) => Math.max(m, Number(r.attempt) || 1), 1);
188
+ if (list.length === 0) return { state: 'none', attempt, runIds, why: 'no run at the batch head yet' };
189
+ const bad = list.find((r) => r.status === 'completed' && r.conclusion !== 'success' && r.conclusion !== 'cancelled');
190
+ if (bad) return { state: 'red', attempt, runIds, why: `a run finished ${bad.conclusion}` };
191
+ if (list.some((r) => r.status !== 'completed')) return { state: 'pending', attempt, runIds, why: 'a run is still in flight' };
192
+ if (list.some((r) => r.conclusion === 'success')) return { state: 'green', attempt, runIds, why: `${list.length} run(s): all success` };
193
+ return { state: 'red', attempt, runIds, why: 'every run was cancelled' };
194
+ }
195
+
196
+ /**
197
+ * The one decision per `colab ship --batch` call. The command is RE-ENTRANT: it reads remote state,
198
+ * takes one step, and exits — the caller waits (bounded, code-ship B1a) and calls again.
199
+ * serial(reason) land nothing; hand the members back as a serial list (exit 4)
200
+ * wait-trunk trunk's own run is still in flight (exit 3)
201
+ * rebuild a batch ref exists on a base trunk has moved past, or its members/heads are
202
+ * no longer the ones asked for → delete it, then build afresh
203
+ * build build + push the batch ref (exit 3)
204
+ * wait-run the combined run is pending or has not appeared (exit 3)
205
+ * red-rerun-or-serial combined run red on its FIRST attempt — the caller classifies it (§4): a
206
+ * red:infra is re-run once, a red:finding goes serial (exit 4, ref kept)
207
+ * red-serial red again after the one re-run — land nothing, serial (exit 4, ref deleted)
208
+ * land green → fast-forward trunk if it has not moved
209
+ */
210
+ function nextStep({ enabled, wired, trunkCi, eligibleCount = 0, existing = null, trunkNow = null, verdict = null }) {
211
+ if (!enabled) return { step: 'serial', reason: 'not-enabled' };
212
+ if (!wired) return { step: 'serial', reason: 'unwired' };
213
+ if (trunkCi === 'red') return { step: 'serial', reason: 'trunk-red' };
214
+ if (trunkCi === 'pending') return { step: 'wait-trunk' };
215
+ if (existing) {
216
+ if (!trunkNow || !String(trunkNow).startsWith(existing.base7)) return { step: 'rebuild', reason: 'trunk-moved' };
217
+ if (!existing.matches) return { step: 'rebuild', reason: 'members-changed' };
218
+ if (!verdict || verdict.state === 'pending' || verdict.state === 'none') return { step: 'wait-run' };
219
+ if (verdict.state === 'red') return verdict.attempt >= 2 ? { step: 'red-serial' } : { step: 'red-rerun-or-serial' };
220
+ return { step: 'land' };
221
+ }
222
+ if (eligibleCount < 2) return { step: 'serial', reason: 'too-few' };
223
+ return { step: 'build' };
224
+ }
225
+
226
+ /**
227
+ * #391: a batch ref sits at the current base carrying a member set OTHER than the one now asked
228
+ * for. Is it still in flight, or already declined? Only a pending/green (or not-yet-run) batch is in
229
+ * flight and may make the new request wait; a red one — first attempt or after its re-run — has
230
+ * been declined (`red-rerun-or-serial` keeps its ref so the one re-run stays possible), and keeping
231
+ * it would block every later batch at this base until trunk moved. So:
232
+ * clear its combined run is red → delete the ref, then build the requested batch
233
+ * wait anything else (pending, none, green, unreadable) → exit 3, exactly as before
234
+ */
235
+ function foreignBatchStep(verdict) {
236
+ return verdict && verdict.state === 'red' ? { step: 'clear', why: verdict.why } : { step: 'wait' };
237
+ }
238
+
239
+ /**
240
+ * Does a green run on the batch ref count as trunk-green for the SAME sha (trunk fast-forwarded to
241
+ * the batch head, so the sha is identical)? Only when the same workflows ran there — a workflow that
242
+ * fires on a trunk push but not on `ship-batch/**` never graded that sha, and its absence is not a
243
+ * pass. So all of:
244
+ * - no trunk run at the sha has finished not-green (a real trunk red always wins);
245
+ * - the batch rows are green (combinedVerdict);
246
+ * - the workflow FILES firing on a trunk push and on a `ship-batch/**` push are the same set;
247
+ * - there are at least as many batch rows as trunk-firing workflows.
248
+ * Anything else → false, and trunk waits for its own run exactly as today.
249
+ */
250
+ function batchGreenCoversTrunk({ trunkRows, batchRows, trunkFires, batchFires }) {
251
+ const t = Array.isArray(trunkRows) ? trunkRows : [];
252
+ if (t.some((r) => r.status === 'completed' && r.conclusion !== 'success' && r.conclusion !== 'cancelled')) return false;
253
+ if (combinedVerdict(batchRows).state !== 'green') return false;
254
+ const a = [...new Set(trunkFires || [])].sort();
255
+ const b = [...new Set(batchFires || [])].sort();
256
+ if (!a.length || a.length !== b.length || a.some((x, i) => x !== b[i])) return false;
257
+ return (batchRows || []).length >= a.length;
258
+ }
259
+
260
+ /** The clause each member's 🚢 evidence comment gains: which combined run graded it. */
261
+ function evidenceSuffix({ n, ref, headSha, runIds }) {
262
+ const runs = (runIds || []).length ? (runIds || []).join(', ') : '(id unread)';
263
+ return ` · landed in a batch of ${n} — combined run ${runs} at ${ref}@${String(headSha || '').slice(0, 7)} (#373)`;
264
+ }
265
+
266
+ /** The line every declined batch ends on — the members, handed back one at a time. */
267
+ function serialLine(branches) {
268
+ const list = (branches || []).filter(Boolean);
269
+ return `→ SERIAL: ${list.map((b) => `colab ship --branch ${b}`).join(' · ') || '(no members)'}`;
270
+ }
271
+
272
+ module.exports = {
273
+ MAX_BATCH, REF_PREFIX, PROBE_REF, TRAILER_KEY,
274
+ parseShipBatch, batchRefName, parseBatchRef, memberTrailer, parseMemberTrailers,
275
+ branchCiClass, memberEligibility, selectMembers, wiring, combinedVerdict, nextStep, foreignBatchStep,
276
+ batchGreenCoversTrunk, evidenceSuffix, serialLine,
277
+ };
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+ /**
3
+ * The two-role session suffix on the comments `colab ship` posts (#372).
4
+ *
5
+ * The comment used to end `· session <name>`, and that name was the session holding the CLAIM,
6
+ * not the session that ran `colab ship`. The sentence around it reads "Shipped … by colab ship —
7
+ * … session X", so a correct ship read as "session X shipped its own work" — the one thing
8
+ * `code-wrap` / `code-ship` keep apart. Measured: 8 of 8 merges in one day on an auto-trunk repo
9
+ * named the implementer; one separate ship session had run every ship; a coordinator read the
10
+ * comments and reported the implementers for self-shipping. Only the transcripts could clear them.
11
+ *
12
+ * So the suffix names both roles, and says which it cannot name:
13
+ *
14
+ * · implemented by session <holder> · shipped by session <shipper>
15
+ * · implemented by session <holder> · shipped by: unknown
16
+ * · implemented and shipped by the same session <x> ← the case a reviewer needs to spot
17
+ *
18
+ * "Same" is decided by the session URL when both sides carry one — that is the only join key.
19
+ * With a URL missing on either side, the names are compared, and a match says so ("matched by
20
+ * name only"), because a name is display text and two sessions can share one. When the two sides
21
+ * share no field at all, the comment says it cannot tell rather than guessing either way.
22
+ *
23
+ * Pure: no git, no I/O, no env. tools/colab resolves both identities (`resolveShipSession`).
24
+ */
25
+
26
+ /** One identity as comment text: `[name](url)` when both, else whichever is set, else ''. */
27
+ function sessionRef(id) {
28
+ const session = (id && id.session) || '';
29
+ const sessionName = (id && id.sessionName) || '';
30
+ if (sessionName && session) return `[${sessionName}](${session})`;
31
+ return session || sessionName;
32
+ }
33
+
34
+ /**
35
+ * Are two identities the same session? `{ same, by }`, or null when they share no field to compare.
36
+ * `by` is 'url' (authoritative) or 'name' (display text — reported as such).
37
+ */
38
+ function compareSessions(a, b) {
39
+ if (a && b && a.session && b.session) return { same: a.session === b.session, by: 'url' };
40
+ if (a && b && a.sessionName && b.sessionName) return { same: a.sessionName === b.sessionName, by: 'name' };
41
+ return null;
42
+ }
43
+
44
+ /**
45
+ * The ` · implemented by … · shipped by …` suffix. Never '' — an unknown role is written as
46
+ * `unknown`, because leaving it out is exactly the ambiguity #372 removes.
47
+ *
48
+ * @param {{session?: string, sessionName?: string}} holder the session holding the claim / worktree
49
+ * @param {{session?: string, sessionName?: string}} shipper the session that ran `colab ship`
50
+ */
51
+ function shipRolesSuffix(holder, shipper) {
52
+ const h = sessionRef(holder);
53
+ const s = sessionRef(shipper);
54
+ if (!h && !s) return ' · implemented by: unknown · shipped by: unknown';
55
+ if (!s) return ` · implemented by session ${h} · shipped by: unknown`;
56
+ if (!h) return ` · implemented by: unknown · shipped by session ${s}`;
57
+ const cmp = compareSessions(holder, shipper);
58
+ if (cmp && cmp.same) {
59
+ // Merge the two records: either side may carry the half the other lacks.
60
+ const merged = sessionRef({
61
+ session: holder.session || shipper.session,
62
+ sessionName: holder.sessionName || shipper.sessionName,
63
+ });
64
+ const how = cmp.by === 'name' ? ' (matched by name only — no session URL on one side)' : '';
65
+ return ` · implemented and shipped by the same session ${merged}${how}`;
66
+ }
67
+ const note = cmp ? '' : ' (no shared identity field — cannot tell whether these are one session)';
68
+ return ` · implemented by session ${h} · shipped by session ${s}${note}`;
69
+ }
70
+
71
+ module.exports = { shipRolesSuffix, compareSessions, sessionRef };
@@ -0,0 +1,181 @@
1
+ 'use strict';
2
+ /**
3
+ * `colab ship` precondition (#322): is the LOCAL merge target in sync with `origin/<target>`?
4
+ *
5
+ * WHY THIS EXISTS — it is not tidiness, it is the door that produced a guard bypass.
6
+ *
7
+ * `ship` squash-merges into the target checkout and THEN pushes it (B1, then B2). Until this
8
+ * check, the only thing standing between those two steps and reality was "trunk checkout ready",
9
+ * which asks whether the checkout is ON trunk and CLEAN — never whether the local ref agrees with
10
+ * the remote. A trunk that was fetched but never fast-forwarded, or that carries a hand-made
11
+ * commit, passes that row unchanged. So B1 completed a merge that B2 could not publish, and the
12
+ * session was left holding a landed local merge with no sanctioned way forward. The refusal it
13
+ * then hit — `pre-push-guard`'s — named the environment variable that opens the guard, so the
14
+ * only visible exit was the bypass. Two independent sessions took it on the same day, one of them
15
+ * reporting it as ordinary housekeeping.
16
+ *
17
+ * Hardening the guard alone would have converted that bypass into a hard stall. This check is the
18
+ * other half: the disagreement is discovered BEFORE the merge, while the remedy is still an
19
+ * ordinary git command instead of an authorization assertion.
20
+ *
21
+ * TWO CLASSES, NOT ONE — and the distinction is the whole point of reporting them separately:
22
+ * - BEHIND only → mechanical. A clean checkout strictly behind its remote fast-forwards
23
+ * losslessly; nobody has to decide anything, so this is SELF-CLEARING.
24
+ * - AHEAD (or DIVERGED) → a judgement call. Those commits are unpublished work sitting on a
25
+ * branch that is push-guarded on purpose. The remedy is to move them onto a session branch and
26
+ * ship THAT — never to publish them by hand, which is exactly the act the guard exists to
27
+ * refuse. HUMAN-GATED.
28
+ *
29
+ * NOTHING IN THIS FILE NAMES AN ENVIRONMENT VARIABLE, deliberately. A refusal message is read by
30
+ * an agent looking for the next command to type; whatever it names is what gets typed. It names
31
+ * the remedy.
32
+ *
33
+ * `ship` does not fast-forward for you, even in the mechanical case. The write would land in the
34
+ * shared trunk checkout BEFORE ship acquires that checkout's place-claim (which it takes at B1,
35
+ * see #234) — writing into a tree another session may be holding, to save one command, is the
36
+ * trade this repo has repeatedly declined.
37
+ */
38
+
39
+ /** The precondition's row name — one spelling, shared by the prose table and `--dry --json`. */
40
+ const NAME = 'target in sync with origin';
41
+
42
+ /**
43
+ * Pure classifier: counts in, verdict out. No git, no io — every branch below is reachable from a
44
+ * plain object, which is what makes the four cases testable without a network or a fixture.
45
+ *
46
+ * @param {object} a
47
+ * @param {string} a.target - the branch being merged INTO (trunk, or a declared line)
48
+ * @param {boolean} a.fetched - did the remote-tracking ref get refreshed?
49
+ * @param {string} [a.why] - when `fetched` is false, why not (verbatim, for the detail line)
50
+ * @param {number} [a.ahead] - commits on local `<target>` that `origin/<target>` does not have
51
+ * @param {number} [a.behind] - commits on `origin/<target>` that local `<target>` does not have
52
+ * @param {string} [a.repoLabel] - what to put after `git -C` in the remedy (default `<repo>`)
53
+ * @param {string} [a.remote] - the repo's resolved remote (#301; default `origin`)
54
+ * @returns {{ok: boolean, cls: string, name: string, detail: string, remedy: string[]}}
55
+ */
56
+ function classifyTargetSync(a) {
57
+ const target = a.target;
58
+ const repo = a.repoLabel || '<repo>';
59
+ const remoteName = a.remote || 'origin';
60
+ const remote = `${remoteName}/${target}`;
61
+
62
+ if (!a.fetched) {
63
+ return {
64
+ ok: false,
65
+ cls: 'unknown',
66
+ name: NAME,
67
+ detail: `could not compare local ${target} with ${remote}: ${a.why || 'unknown reason'}`,
68
+ remedy: [
69
+ `Cannot tell whether ${target} is publishable, and a merge that cannot be pushed is the`,
70
+ 'state this check exists to prevent. Restore the comparison, then re-run this ship:',
71
+ ` git -C ${repo} fetch ${remoteName} ${target}`,
72
+ ],
73
+ };
74
+ }
75
+
76
+ const ahead = Number(a.ahead || 0);
77
+ const behind = Number(a.behind || 0);
78
+
79
+ if (ahead === 0 && behind === 0) {
80
+ return { ok: true, cls: 'synced', name: NAME, detail: `local ${target} == ${remote}`, remedy: [] };
81
+ }
82
+
83
+ const plural = (n) => (n === 1 ? 'commit' : 'commits');
84
+
85
+ if (ahead === 0) {
86
+ return {
87
+ ok: false,
88
+ cls: 'behind',
89
+ name: NAME,
90
+ detail: `local ${target} is ${behind} ${plural(behind)} behind ${remote} — the merge would land on a stale base and the push would be rejected`,
91
+ remedy: [
92
+ `Fast-forward the checkout, then re-run this ship (nothing here needs a decision):`,
93
+ ` git -C ${repo} merge --ff-only ${remote}`,
94
+ ],
95
+ };
96
+ }
97
+
98
+ const strayLines = [
99
+ `The ${ahead} unpublished ${plural(ahead)} on ${target} ${ahead === 1 ? 'is' : 'are'} work that never went through a branch.`,
100
+ `Publishing ${ahead === 1 ? 'it' : 'them'} straight from here is the act ${target} is push-guarded to refuse — move`,
101
+ `${ahead === 1 ? 'it' : 'them'} onto a session branch and ship that instead:`,
102
+ ` git -C ${repo} log --oneline ${remote}..${target} # what is actually there`,
103
+ ` git -C ${repo} branch <type>/<slug>-<issue> ${target} # keep it, on a branch`,
104
+ ` git -C ${repo} reset --hard ${remote} # return the checkout to at-rest`,
105
+ `then claim its issue and ship that branch. If the ${plural(ahead)} ${ahead === 1 ? 'was' : 'were'} never wanted, the reset`,
106
+ 'alone is the whole remedy.',
107
+ ];
108
+
109
+ if (behind === 0) {
110
+ return {
111
+ ok: false,
112
+ cls: 'ahead',
113
+ name: NAME,
114
+ detail: `local ${target} has ${ahead} unpushed ${plural(ahead)} ${remote} does not — merging on top would produce a commit ship cannot publish`,
115
+ remedy: strayLines,
116
+ };
117
+ }
118
+
119
+ return {
120
+ ok: false,
121
+ cls: 'diverged',
122
+ name: NAME,
123
+ detail: `local ${target} has ${ahead} unpushed ${plural(ahead)} and is ${behind} behind ${remote} — diverged`,
124
+ remedy: strayLines.concat([
125
+ `Then fast-forward before re-running: git -C ${repo} merge --ff-only ${remote}`,
126
+ ]),
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Read the counts from git and classify. Best-effort fetch first — a comparison against a
132
+ * remote-tracking ref nobody refreshed answers the wrong question with total confidence, the same
133
+ * failure `colab holders` refuses rather than guesses through.
134
+ *
135
+ * @param {object} git - tools/lib/git (injected so the classifier above stays io-free)
136
+ * @param {string} repoAbs - the MAIN checkout (where the target branch ref lives)
137
+ * @param {string} target - branch being merged into
138
+ * @param {object} [opts]
139
+ * @param {string} [opts.repoLabel] - label for the remedy commands (defaults to `repoAbs`)
140
+ * @param {boolean} [opts.fetch] - set false to compare against whatever is already on disk
141
+ */
142
+ function readTargetSync(git, repoAbs, target, opts = {}) {
143
+ const repoLabel = opts.repoLabel || repoAbs;
144
+ const base = { target, repoLabel };
145
+ // #301: the repo's resolved remote, not the literal `origin`. An unresolvable one (ambiguous, or a
146
+ // broken `colab.remote`) is reported as the comparison failing, with the fix, never guessed through.
147
+ const info = git.remoteInfo(repoAbs);
148
+ const problem = git.remoteProblem(info);
149
+ if (problem) return classifyTargetSync({ ...base, fetched: false, why: problem });
150
+ if (!info.name || !git.remoteUrl(repoAbs)) {
151
+ return classifyTargetSync({ ...base, fetched: false, why: 'this repo has no `origin` remote' });
152
+ }
153
+ const remote = info.name;
154
+ base.remote = remote;
155
+ if (opts.fetch !== false) {
156
+ const f = git.git(['fetch', remote, target], repoAbs, { timeoutMs: 60000 });
157
+ if (!f.ok) {
158
+ return classifyTargetSync({
159
+ ...base, fetched: false,
160
+ why: `git fetch ${remote} ${target} failed: ${(f.stderr || 'unknown error').split('\n')[0]}`,
161
+ });
162
+ }
163
+ }
164
+ // `--count --left-right A...B` → "<behind-of-A>\t<ahead-of-A>" is the reading that trips people
165
+ // up; spell the two sides out rather than rely on remembering which column is which.
166
+ const counts = git.git(['rev-list', '--left-right', '--count', `${remote}/${target}...${target}`], repoAbs);
167
+ if (!counts.ok) {
168
+ return classifyTargetSync({
169
+ ...base, fetched: false,
170
+ why: `could not count commits against ${remote}/${target}: ${(counts.stderr || 'unknown error').split('\n')[0]}`,
171
+ });
172
+ }
173
+ const parts = counts.stdout.split(/\s+/).filter(Boolean).map(Number);
174
+ if (parts.length !== 2 || parts.some((n) => !Number.isFinite(n))) {
175
+ return classifyTargetSync({ ...base, fetched: false, why: `unreadable rev-list output: "${counts.stdout}"` });
176
+ }
177
+ // left = <remote>/<target> side = commits local is BEHIND by; right = local side = AHEAD by.
178
+ return classifyTargetSync({ ...base, fetched: true, behind: parts[0], ahead: parts[1] });
179
+ }
180
+
181
+ module.exports = { NAME, classifyTargetSync, readTargetSync };