@futurelastic/colab-handbook 1.12.0-rc.10 → 1.12.0-rc.12

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.
package/README.md CHANGED
@@ -187,6 +187,7 @@ you want.
187
187
  | `--hooks` | Point this clone's git at `.githooks/`, whose `pre-commit` runs every check in `pre-commit.d/` — a gitleaks secret scan, and an identity scan that needs a vocabulary you supply by path and keep outside every repo (see [`templates/README.md`](templates/README.md)). `core.hooksPath` lives in `.git/config`, so it is per-clone, per-machine, and never travels with the repo. |
188
188
  | `--fleet` | Seed `~/.colab/repos.txt` from `audit/repos.txt`, only if it is absent. The seed is format notes and commented placeholders — it registers **nothing**; `colab register <path>` (step 3) is what fills it. That list stays machine-local on purpose: it names your private repos, and this repo is public. |
189
189
  | `--all` | `--tools --hooks --fleet`. |
190
+ | `--notify-url <url>` | Seed `notifyUrl` in `~/.colab/config.json` with a local observer's events URL, only when the key is absent — an existing value is never overwritten. Without the flag, `--tools` seeds it from `~/.colab/notify-endpoint` when a local observer declared its URL there, and otherwise prints that `notifyUrl` is unset and which events that drops. See [`tools/README.md`](tools/README.md#notifyurl--optional-event-push-off-by-default). |
190
191
  | `--dry` | Print what would happen, change nothing. Combines with all of the above. |
191
192
  | `--check` | **Read-only** health report on what an earlier install left behind — see *Checking an install* below. Takes no other flag; exit 1 on any ✗ row. |
192
193
 
@@ -246,8 +247,9 @@ A frozen copy never breaks — it gets **old**, and an old complete copy answers
246
247
  normally for every command it knows until something asks for one added after it
247
248
  was frozen. `--check` is the report nothing else gives: whether the frozen copy is
248
249
  behind the latest release, **which commands it does not dispatch**, whether the
249
- state file exists, whether anything is registered, and whether both pre-commit
250
- hooklets can actually run (gitleaks, and the identity vocabulary). ✗ means
250
+ state file exists, whether anything is registered, whether both pre-commit
251
+ hooklets can actually run (gitleaks, and the identity vocabulary), and whether
252
+ `notifyUrl` is unset while a local observer declared an endpoint. ✗ means
251
253
  something installed here is stale or unusable; ⚠ means something was never set
252
254
  up, which may be deliberate. It never refreshes anything — re-freezing stays your
253
255
  call: `./install.sh --tools`.
package/README.vi.md CHANGED
@@ -185,6 +185,7 @@ nếu bạn thật sự chỉ cần bấy nhiêu.
185
185
  | `--hooks` | Trỏ git của clone này vào `.githooks/`, ở đó `pre-commit` chạy lần lượt mọi check trong `pre-commit.d/` — quét secret bằng gitleaks, và quét danh tính (identity) vốn cần một danh sách từ khoá do bạn cấp bằng đường dẫn và giữ NGOÀI mọi repo (xem [`templates/README.md`](templates/README.md)). `core.hooksPath` nằm trong `.git/config` nên là cấu hình per-clone, per-máy, không đi theo repo. |
186
186
  | `--fleet` | Tạo `~/.colab/repos.txt` từ `audit/repos.txt`, chỉ khi file chưa tồn tại. Danh sách đó cố tình nằm ngoài repo: nó ghi tên các repo private của bạn, còn repo này thì public. |
187
187
  | `--all` | `--tools --hooks --fleet`. |
188
+ | `--notify-url <url>` | Ghi `notifyUrl` vào `~/.colab/config.json` bằng URL nhận event của một observer chạy trên máy, chỉ khi khoá đó chưa có — giá trị đang có không bao giờ bị ghi đè. Không truyền flag thì `--tools` lấy URL từ `~/.colab/notify-endpoint` nếu observer trên máy đã khai ở đó; không có thì in rõ `notifyUrl` đang trống và sẽ mất những event nào. Xem [`tools/README.md`](tools/README.md#notifyurl--optional-event-push-off-by-default). |
188
189
  | `--dry` | In ra sẽ làm gì, không thay đổi gì. Ghép được với mọi flag trên. |
189
190
 
190
191
  **Service luôn-bật phải gọi `~/.colab/bin/colab`.** Bản CLI symlink chạy theo
package/package.json CHANGED
@@ -27,5 +27,5 @@
27
27
  "engines": {
28
28
  "node": ">=18"
29
29
  },
30
- "version": "1.12.0-rc.10"
30
+ "version": "1.12.0-rc.12"
31
31
  }
package/tools/colab CHANGED
@@ -22,6 +22,7 @@ const squash = require('./lib/squash');
22
22
  const procs = require('./lib/procs');
23
23
  const landed = require('./lib/landed');
24
24
  const notify = require('./lib/notify');
25
+ const notifyEndpoint = require('./lib/notify-endpoint'); // #414
25
26
  const journal = require('./lib/journal');
26
27
  const labels = require('./lib/labels');
27
28
  const records = require('./lib/records');
@@ -56,6 +57,7 @@ const claimComments = require('./lib/claim-comments');
56
57
  const machine = require('./lib/machine');
57
58
  const targetSync = require('./lib/ship-target-sync');
58
59
  const shipBatch = require('./lib/ship-batch');
60
+ const conflictMarkers = require('./lib/conflict-markers');
59
61
  const docsOnly = require('./lib/docs-only');
60
62
  const cureDiff = require('./lib/cure-diff');
61
63
  const codeowners = require('./lib/codeowners');
@@ -4871,6 +4873,19 @@ function worktreeSubdir(config) { return config.worktreeSubdir || '.worktrees';
4871
4873
  // slow-but-working. Overridable per-machine/per-repo for a legitimately slow teardown.
4872
4874
  const TEARDOWN_TIMEOUT_MS = Number(process.env.COLAB_TEARDOWN_TIMEOUT_MS) || 5 * 60 * 1000;
4873
4875
 
4876
+ /**
4877
+ * #436: after a pre-ship hook exits 0, which of the paths it was handed still carry conflict markers
4878
+ * in the index — i.e. would be committed with `<<<<<<<` in them. Untrimmed git output, so the line
4879
+ * numbers in the message are the file's own.
4880
+ */
4881
+ function stagedConflictMarkers(dir, paths) {
4882
+ const rawGit = (args, cwd) => {
4883
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
4884
+ return { ok: r.status === 0, stdout: r.stdout || '' };
4885
+ };
4886
+ return conflictMarkers.stagedMarkerPaths(rawGit, dir, paths);
4887
+ }
4888
+
4874
4889
  function runHook(repoAbs, name, ctx) {
4875
4890
  const hook = path.join(repoAbs, '.colab', 'hooks', name);
4876
4891
  try {
@@ -5713,6 +5728,11 @@ claims from.
5713
5728
  "contained in trunk" between releases BY CONSTRUCTION, which this heuristic would otherwise
5714
5729
  misread as spent and advise deleting, silently breaking GitOps deploys (#63).
5715
5730
 
5731
+ - \`notifyUrl: unset\` is reported (read-only, never pruned, not part of the verdict) when a
5732
+ local observer declared its events URL in <COLAB_HOME>/notify-endpoint and notifyUrl is not
5733
+ set — that observer then receives no issue.merged / issue.closed / readiness.marked /
5734
+ gate.recorded event (#414). No declared endpoint, no line: unset is the right default there.
5735
+
5716
5736
  This exists because claims made without a worktree were never auto-healed before, and a
5717
5737
  real repo accumulated 17 stale same-day claims. Run \`colab doctor\` regularly; \`--prune\`
5718
5738
  in a cleanup cron.
@@ -6203,6 +6223,11 @@ function cmdDoctor(argv) {
6203
6223
  }
6204
6224
  }
6205
6225
 
6226
+ // 10. notifyUrl against a DECLARED local observer (#414). Read-only, never pruned, never counted in
6227
+ // the verdict — it is configuration, not state drift. Silent on a machine with no
6228
+ // <COLAB_HOME>/notify-endpoint: unset is the right default where no observer runs.
6229
+ report.notify = notifyEndpoint.status(config, state.COLAB_DIR);
6230
+
6206
6231
  if (opts.json) { print(JSON.stringify(report, null, 2)); return 0; }
6207
6232
 
6208
6233
  const verb = opts.prune ? 'Pruned' : 'Found';
@@ -6407,6 +6432,11 @@ function cmdDoctor(argv) {
6407
6432
  print(' which also stops colab handing it to a worktree. A "cwd DELETED" line above is the real');
6408
6433
  print(' orphan and wants killing, not reserving.');
6409
6434
  }
6435
+ const notifyLine = notifyEndpoint.healthLine(report.notify);
6436
+ if (notifyLine) {
6437
+ print('');
6438
+ print(notifyLine);
6439
+ }
6410
6440
  return 0;
6411
6441
  }
6412
6442
 
@@ -9423,8 +9453,12 @@ for is built in its place, so the survivors of a decline can batch without landi
9423
9453
  A member that conflicts with the members already in is dropped to the next batch; the rest go on —
9424
9454
  unless every conflicting path is generated (defaults + project.yml generated:): then .colab/hooks/pre-ship
9425
9455
  regenerates them on the combined head and the member stays in (#387). No hook, or a failing one → dropped.
9426
- --dry builds the batch locally and prints it, pushing nothing. Consumer CI must opt in: add
9427
- 'ship-batch/**' to a CI workflow's push: branches:.
9456
+ A hook that exits 0 but leaves a <<<<<<< / >>>>>>> line staged in a path it was handed counts as failing (#436).
9457
+ Resuming a staged batch: a branch you name that the staged batch does not carry (over the cap, dropped
9458
+ at build, added since) is NOT landed with it — the command names both lists and says so (#415).
9459
+ --dry pushes, deletes, lands, comments and releases nothing on EVERY path (#415): a fresh batch is built
9460
+ locally and printed; a staged green batch prints what would land (members, combined run, target sha).
9461
+ Consumer CI must opt in: add 'ship-batch/**' to a CI workflow's push: branches:.
9428
9462
 
9429
9463
  B3 KEEPS the branch by default. Deleting refs from a shared remote is not something this command
9430
9464
  does unasked, however certain it is that the content landed: reporting is safe and reversible,
@@ -11833,6 +11867,14 @@ function cmdShip(argv) {
11833
11867
  }
11834
11868
  if (hasPreShip) {
11835
11869
  const hk = runHook(repoAbs, 'pre-ship', { wtPath: branchDir, name: sess.name || sess.branch, branch: sess.branch, ports: [], trunk, base: target, issues: sess.issues });
11870
+ // #436: exit 0 is the hook's claim; the index is the proof. Markers left in a path it was
11871
+ // handed make it a failing hook, checked BEFORE the commit so nothing carrying them is pushed.
11872
+ const markers = hk.ran && hk.ok ? stagedConflictMarkers(branchDir, uf) : [];
11873
+ if (markers.length) {
11874
+ git.git(['merge', '--abort'], branchDir); cleanupEphemeral();
11875
+ process.stderr.write(`✗ B0: pre-ship hook exited 0 but left conflict markers staged in ${conflictMarkers.describe(markers)} — treated as a failing hook. Nothing pushed.\n`);
11876
+ return 1;
11877
+ }
11836
11878
  const committed = hk.ran && hk.ok && git.git(['commit', '--no-edit'], branchDir).ok;
11837
11879
  if (!committed) {
11838
11880
  git.git(['merge', '--abort'], branchDir); cleanupEphemeral();
@@ -12477,7 +12519,9 @@ function cmdShipBatch(opts) {
12477
12519
  const batchRefs = (lsBatch.ok ? lsBatch.stdout.split('\n') : []).map((l) => l.split('\t'))
12478
12520
  .map(([sha, ref]) => ({ sha: (sha || '').trim(), parsed: shipBatch.parseBatchRef((ref || '').trim()) }))
12479
12521
  .filter((x) => x.sha && x.parsed);
12522
+ // #415: every write on the resume path goes through here or shipBatchLand — under --dry, neither writes.
12480
12523
  const deleteRef = (ref) => {
12524
+ if (opts.dry) { print(` [dry] would delete ${remote}/${ref}`); return true; }
12481
12525
  const d = git.git(['push', remote, '--delete', ref], repoAbs);
12482
12526
  if (!d.ok) warn(`could not delete ${remote}/${ref}: ${git.gitFailureLine(d.stderr)} — delete it by hand`);
12483
12527
  return d.ok;
@@ -12507,6 +12551,14 @@ function cmdShipBatch(opts) {
12507
12551
  const heads = inBatch.map((m) => ({ ...m, now: git.branchRefs(repoAbs, m.branch, remote).remoteSha }));
12508
12552
  const matches = heads.length >= 2 && heads.every((m) => m.now && m.now.startsWith(m.sha));
12509
12553
  existing = { ref: atBase.parsed.ref, base7: atBase.parsed.base7, sha: atBase.sha, members: inBatch, matches };
12554
+ // #415: the command line and the staged batch can name different sets. A requested branch the
12555
+ // staged batch does not carry (over the cap, dropped at build, or added since) does NOT ride
12556
+ // along — say so, naming both lists, instead of resuming as if the two were the same.
12557
+ const notStaged = shipBatch.notStaged(members, inBatch);
12558
+ if (notStaged.length) {
12559
+ print(` ! ${atBase.parsed.ref} was staged with ${inBatch.map((m) => m.branch).join(', ')}; this command named ${members.join(', ')}.`);
12560
+ print(` NOT in the staged batch, so it does not land with it: ${notStaged.join(', ')} — ship it after this batch (next batch, or colab ship --branch <b>).`);
12561
+ }
12510
12562
  }
12511
12563
  }
12512
12564
  const verdict = existing && existing.matches ? shipBatch.combinedVerdict(git.ghRunsForRef(repoAbs, existing.ref, existing.sha)) : null;
@@ -12533,7 +12585,7 @@ function cmdShipBatch(opts) {
12533
12585
  return 4;
12534
12586
  }
12535
12587
  if (step.step === 'red-serial') {
12536
- print(`✗ ship-batch: the combined run is red again after its one re-run (${verdict.why}) — nothing landed; ${existing.ref} deleted.`);
12588
+ print(`✗ ship-batch: the combined run is red again after its one re-run (${verdict.why}) — nothing landed; ${existing.ref} ${opts.dry ? 'would be deleted [DRY RUN]' : 'deleted'}.`);
12537
12589
  deleteRef(existing.ref);
12538
12590
  print(shipBatch.serialLine(existing.members.map((m) => m.branch)));
12539
12591
  return 4;
@@ -12600,8 +12652,13 @@ function cmdShipBatch(opts) {
12600
12652
  issues: (m.report && m.report.closeIssues) || [],
12601
12653
  });
12602
12654
  const left = hk.ran ? unmergedIn() : unmerged;
12655
+ // #436: a hook that exits 0 and `git add`s a path still holding markers clears the unmerged
12656
+ // state, so `left` reads empty — read the staged content itself before trusting it.
12657
+ const markers = hk.ran && hk.ok && !left.length ? stagedConflictMarkers(dir, unmerged) : [];
12603
12658
  if (!hk.ran || !hk.ok || left.length) {
12604
12659
  why = `.colab/hooks/pre-ship could not regenerate ${unmerged.join(', ')} on the combined head${left.length && hk.ok ? ` (still unmerged: ${left.join(', ')})` : ''} — next batch`;
12660
+ } else if (markers.length) {
12661
+ why = `.colab/hooks/pre-ship exited 0 but left conflict markers staged in ${conflictMarkers.describe(markers)} on the combined head — treated as a failing hook, next batch`;
12605
12662
  } else regenerated = unmerged;
12606
12663
  }
12607
12664
  if (why) {
@@ -12668,6 +12725,14 @@ function cmdShipBatch(opts) {
12668
12725
  */
12669
12726
  function shipBatchLand(repoAbs, doc, trunk, remote, base, existing, verdict, opts) {
12670
12727
  const head = existing.sha;
12728
+ // #415: a staged green batch reached under --dry is a read: what WOULD land, and nothing else —
12729
+ // no fast-forward, no push, no ref delete, no hook, no worktree teardown, no claim, no comment.
12730
+ if (opts.dry) {
12731
+ print(`ship --batch ${shortRepo(repoAbs)} → ${trunk} @ ${shortSha(base)} [DRY RUN]`);
12732
+ print(`→ READY: would fast-forward ${trunk} ${shortSha(base)} → ${shortSha(head)} — ${existing.ref}, combined run ${(verdict.runIds || []).join(', ') || '(id unread)'} ${verdict.why || verdict.state}`);
12733
+ print(` would land ${existing.members.length} member(s), one squash each: ${existing.members.map((m) => m.branch).join(', ')}`);
12734
+ return 0;
12735
+ }
12671
12736
  const headBranch = git.git(['rev-parse', '--abbrev-ref', 'HEAD'], repoAbs).stdout;
12672
12737
  if (headBranch !== trunk || git.dirtyTracked(repoAbs)) {
12673
12738
  throw new UserError(`the main checkout is not on a clean ${trunk} ("${headBranch}"${git.dirtyTracked(repoAbs) ? ', dirty' : ''}) — the batch is green and waiting; fix the checkout and run this command again`);
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+ /**
3
+ * #436: a pre-ship hook's exit code is a claim ("ZERO means every conflicted path was resolved"),
4
+ * not proof. A hook that regenerates a path's NEW layout and then `git add`s an OLD path still full
5
+ * of conflict markers exits 0 and stages the markers — git clears the unmerged state on `add`, so
6
+ * `git diff --diff-filter=U` reads clean. This reads what would actually be committed.
7
+ *
8
+ * Detection is deliberately `<<<<<<<` / `>>>>>>>` at column 0 (followed by a space or end of line).
9
+ * A bare `=======` line is NOT a marker on its own: it is also a legitimate Markdown setext-heading
10
+ * underline, and generated docs are exactly the files this check reads. Every real conflict block
11
+ * carries the two outer markers, so nothing is missed by not counting the middle one alone.
12
+ */
13
+
14
+ const MARKER = /^(<{7}|>{7})(?:[ \t]|$)/;
15
+
16
+ /** Pure: 1-based line numbers of conflict-marker lines in `text`. */
17
+ function markerLines(text) {
18
+ const out = [];
19
+ String(text == null ? '' : text).split('\n').forEach((line, i) => {
20
+ if (MARKER.test(line.replace(/\r$/, ''))) out.push(i + 1);
21
+ });
22
+ return out;
23
+ }
24
+
25
+ /**
26
+ * Which of `paths` still hold conflict markers in the INDEX (stage 0 — what `git commit` takes) at
27
+ * `cwd`. `gitFn(args, cwd)` → `{ ok, stdout }`. A path absent from the index (deleted, or still
28
+ * unmerged at stages 1-3) is skipped here: deletion is a resolution, and an unmerged path is the
29
+ * caller's existing `--diff-filter=U` check. Returns `[{ path, lines }]`.
30
+ */
31
+ function stagedMarkerPaths(gitFn, cwd, paths) {
32
+ const hits = [];
33
+ for (const p of [...new Set(paths || [])]) {
34
+ const r = gitFn(['show', `:0:${p}`], cwd);
35
+ if (!r || !r.ok) continue;
36
+ const lines = markerLines(r.stdout);
37
+ if (lines.length) hits.push({ path: p, lines });
38
+ }
39
+ return hits;
40
+ }
41
+
42
+ /** One line naming each path and its first marker lines. */
43
+ function describe(hits) {
44
+ return (hits || []).map((h) => `${h.path}:${h.lines.slice(0, 3).join(',')}${h.lines.length > 3 ? ',…' : ''}`).join(', ');
45
+ }
46
+
47
+ module.exports = { markerLines, stagedMarkerPaths, describe };
@@ -25,6 +25,7 @@ const fs = require('fs');
25
25
  const path = require('path');
26
26
  const { execFileSync } = require('child_process');
27
27
  const stamp = require('./stamp');
28
+ const notifyEndpoint = require('./notify-endpoint');
28
29
 
29
30
  const OK = 'ok';
30
31
  const WARN = 'warn';
@@ -218,6 +219,23 @@ function checkHooks({ root, colabHome, home, env }) {
218
219
  return rows;
219
220
  }
220
221
 
222
+ /**
223
+ * notifyUrl against a DECLARED local observer (#414). Silent unless something says an observer runs
224
+ * here: a machine with no <COLAB_HOME>/notify-endpoint gets no row at all — unset is the right default
225
+ * there, and a ⚠ on every such machine would teach people to ignore the row. ⚠ rather than ✗: the
226
+ * key is something never set up, not something installed that went stale.
227
+ */
228
+ function checkNotify({ colabHome }) {
229
+ let cfg = {};
230
+ try { cfg = JSON.parse(readText(path.join(colabHome, 'config.json')) || '{}'); } catch (_) { /* reported by colab itself */ }
231
+ const st = notifyEndpoint.status(cfg, colabHome);
232
+ if (st.state === 'unset') return [];
233
+ if (st.state === 'set' && !st.declared) {
234
+ return [{ area: 'notify', severity: OK, text: `notifyUrl = ${st.url}` }];
235
+ }
236
+ return [{ area: 'notify', severity: WARN, text: notifyEndpoint.healthLine(st) }];
237
+ }
238
+
221
239
  function runChecks(opts) {
222
240
  const o = { env: process.env, ...opts };
223
241
  return [
@@ -226,6 +244,7 @@ function runChecks(opts) {
226
244
  checkState(o),
227
245
  ...checkFleet(o),
228
246
  ...checkHooks(o),
247
+ ...checkNotify(o),
229
248
  ];
230
249
  }
231
250
 
@@ -255,5 +274,5 @@ if (require.main === module) {
255
274
 
256
275
  module.exports = {
257
276
  OK, WARN, FAIL,
258
- dispatchedCommands, checkLink, checkFrozen, checkState, checkFleet, checkHooks, runChecks, render,
277
+ dispatchedCommands, checkLink, checkFrozen, checkState, checkFleet, checkHooks, checkNotify, runChecks, render,
259
278
  };
@@ -0,0 +1,170 @@
1
+ 'use strict';
2
+ /**
3
+ * notify-endpoint.js — is this machine's `notifyUrl` set, and SHOULD it be? (#414)
4
+ *
5
+ * `notifyUrl` is optional by design (lib/notify.js): unset means colab makes no network call of its
6
+ * own, and silence is the right behaviour on a machine with no observer. But a machine that DOES run
7
+ * a local observer (a companion dashboard ingesting `issue.merged`, `issue.closed`,
8
+ * `readiness.marked`, `gate.recorded`) depends on the push for the kinds it cannot recover by
9
+ * polling state.json, and an unset key there is a silent outage. Measured on a two-machine fleet
10
+ * running the same observer: the machine set up by hand had recorded 2 292 `issue.merged` events;
11
+ * the one set up a month later with install.sh had 0, and nothing said so until someone asked for
12
+ * lead time.
13
+ *
14
+ * Two inputs answer "should it be set", and colab guesses neither:
15
+ *
16
+ * 1. an explicit URL a human passes to `install.sh --notify-url <url>`;
17
+ * 2. the DECLARED ENDPOINT FILE, `<COLAB_HOME>/notify-endpoint` — the convention by which a local
18
+ * observer announces itself. The observer writes its own events URL there (one http(s) URL on
19
+ * the first non-comment line); colab only reads it. No port is probed and no well-known URL is
20
+ * hard-coded: an observer's address is the observer's fact, not the handbook's.
21
+ *
22
+ * What reads this:
23
+ * - install.sh seeds `notifyUrl` from (1), else (2), ONLY when the key is absent — an existing
24
+ * value is someone's deliberate choice and is never overwritten. When nothing seeds it, install
25
+ * says plainly that the key is unset and what that costs.
26
+ * - `install.sh --check` and `colab doctor` report `notifyUrl: unset` when (2) exists and the key
27
+ * does not. No declared endpoint → nothing is reported: silence stays right for a machine with
28
+ * no observer.
29
+ *
30
+ * CommonJS, zero dependencies. Runnable as a script (install.sh's entry):
31
+ * node tools/lib/notify-endpoint.js seed --colab-home <dir> [--url <url>] [--dry]
32
+ * It writes config.json through lib/state.js, the CLI's own writer, so the file's shape cannot drift
33
+ * from what `colab config set` produces. state.js reads COLAB_HOME at require time, so the entry
34
+ * sets it from --colab-home before requiring it.
35
+ */
36
+
37
+ const fs = require('fs');
38
+ const path = require('path');
39
+
40
+ const ENDPOINT_FILE = 'notify-endpoint';
41
+ const HTTP_RE = /^https?:\/\//i;
42
+
43
+ /** The event kinds a local observer only learns of by push — named in the "unset" line. */
44
+ const PUSH_ONLY_KINDS = Object.freeze(['issue.merged', 'issue.closed', 'readiness.marked', 'gate.recorded']);
45
+
46
+ function endpointFile(colabHome) {
47
+ return path.join(colabHome, ENDPOINT_FILE);
48
+ }
49
+
50
+ /**
51
+ * Read the declared endpoint. Returns null when no file exists (the common, silent case), else
52
+ * `{ file, url }` for a usable URL or `{ file, invalid }` naming what is wrong with it — a declared
53
+ * endpoint that cannot be used is reported, never silently treated as absent.
54
+ */
55
+ function readDeclared(colabHome) {
56
+ const file = endpointFile(colabHome);
57
+ let raw;
58
+ try { raw = fs.readFileSync(file, 'utf8'); } catch (_) { return null; }
59
+ const line = raw.split(/\r?\n/).map((l) => l.replace(/#.*$/, '').trim()).find(Boolean);
60
+ if (!line) return { file, invalid: 'empty — no URL on any non-comment line' };
61
+ if (!HTTP_RE.test(line)) return { file, invalid: `not an http(s) URL: ${line}` };
62
+ return { file, url: line };
63
+ }
64
+
65
+ function configuredUrl(cfg) {
66
+ return cfg && typeof cfg.notifyUrl === 'string' ? cfg.notifyUrl.trim() : '';
67
+ }
68
+
69
+ /**
70
+ * The read-only verdict both health checks print. `state`:
71
+ * 'set' notifyUrl is configured (payload: url; `declared` when the file names another)
72
+ * 'unset-declared' notifyUrl absent while an observer declared an endpoint — the outage case
73
+ * 'declared-invalid' notifyUrl absent and the declared file is unusable
74
+ * 'unset' neither — a machine with no observer; callers stay silent
75
+ */
76
+ function status(cfg, colabHome) {
77
+ const url = configuredUrl(cfg);
78
+ const declared = readDeclared(colabHome);
79
+ if (url) {
80
+ return declared && declared.url && declared.url !== url
81
+ ? { state: 'set', url, declared }
82
+ : { state: 'set', url };
83
+ }
84
+ if (!declared) return { state: 'unset' };
85
+ if (declared.invalid) return { state: 'declared-invalid', declared };
86
+ return { state: 'unset-declared', declared };
87
+ }
88
+
89
+ /** One human line for a status, or null when the right output is silence. */
90
+ function healthLine(st) {
91
+ if (st.state === 'unset-declared') {
92
+ return `notifyUrl: unset — ${st.declared.file} declares a local observer at ${st.declared.url}, ` +
93
+ `which receives no events (${PUSH_ONLY_KINDS.join(', ')}). Fix: colab config set notifyUrl ${st.declared.url}`;
94
+ }
95
+ if (st.state === 'declared-invalid') {
96
+ return `notifyUrl: unset — ${st.declared.file} is ${st.declared.invalid}, so nothing could be seeded from it`;
97
+ }
98
+ if (st.state === 'set' && st.declared) {
99
+ return `notifyUrl: ${st.url} — differs from the endpoint declared in ${st.declared.file} (${st.declared.url}); ` +
100
+ 'left as configured, check which one the local observer listens on';
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Decide what install.sh does. Pure: returns `{ action, url?, source?, lines[] }` and writes nothing.
107
+ * action 'keep' the key is already set — never overwritten
108
+ * action 'seed' write `url` (from the flag, else the declared file)
109
+ * action 'none' nothing to seed — the lines say plainly the key is unset and what it costs
110
+ */
111
+ function plan({ cfg, colabHome, flagUrl }) {
112
+ const current = configuredUrl(cfg);
113
+ const declared = readDeclared(colabHome);
114
+ if (flagUrl && !HTTP_RE.test(flagUrl)) {
115
+ return { action: 'error', lines: [`--notify-url must be an http(s) URL, got: ${flagUrl}`] };
116
+ }
117
+ if (current) {
118
+ const lines = [`✓ notifyUrl = ${current} (already set → left untouched)`];
119
+ if (flagUrl && flagUrl !== current) {
120
+ lines.push(`⚠ --notify-url ${flagUrl} NOT applied: an existing value is never overwritten. ` +
121
+ `To change it: colab config set notifyUrl ${flagUrl}`);
122
+ }
123
+ const hl = healthLine(status(cfg, colabHome));
124
+ if (hl) lines.push(`⚠ ${hl}`);
125
+ return { action: 'keep', lines };
126
+ }
127
+ if (flagUrl) return { action: 'seed', url: flagUrl, source: '--notify-url', lines: [] };
128
+ if (declared && declared.url) return { action: 'seed', url: declared.url, source: declared.file, lines: [] };
129
+ const lines = [];
130
+ if (declared && declared.invalid) lines.push(`⚠ ${declared.file} is ${declared.invalid} — ignored.`);
131
+ lines.push(
132
+ '⚠ notifyUrl is UNSET — colab pushes no events from this machine.',
133
+ ` A local observer (e.g. a companion dashboard) here will never receive ${PUSH_ONLY_KINDS.join(', ')}.`,
134
+ ' Observer on this machine? Re-run with --notify-url <its events URL>, or: colab config set notifyUrl <url>',
135
+ ' No observer here? Nothing to do — unset is the right default.',
136
+ );
137
+ return { action: 'none', lines };
138
+ }
139
+
140
+ function main(argv) {
141
+ const sub = argv[0];
142
+ const val = (flag) => {
143
+ const i = argv.indexOf(flag);
144
+ return i >= 0 && argv[i + 1] !== undefined ? argv[i + 1] : undefined;
145
+ };
146
+ const colabHome = val('--colab-home') || process.env.COLAB_HOME || path.join(require('os').homedir(), '.colab');
147
+ if (sub !== 'seed') {
148
+ process.stderr.write('usage: notify-endpoint.js seed --colab-home <dir> [--url <url>] [--dry]\n');
149
+ return 2;
150
+ }
151
+ process.env.COLAB_HOME = colabHome; // before state.js computes its paths
152
+ const state = require('./state');
153
+ const cfg = state.loadConfig();
154
+ const p = plan({ cfg, colabHome, flagUrl: val('--url') });
155
+ const out = (l) => process.stdout.write(` ${l}\n`);
156
+ if (p.action === 'error') { process.stderr.write(` ✗ ${p.lines[0]}\n`); return 2; }
157
+ if (p.action !== 'seed') { p.lines.forEach(out); return 0; }
158
+ if (argv.includes('--dry')) { out(`[dry] seed notifyUrl = ${p.url} (from ${p.source})`); return 0; }
159
+ // Re-read inside the write: a key set between plan and write is still never overwritten.
160
+ const fresh = state.loadConfig();
161
+ if (configuredUrl(fresh)) { out(`✓ notifyUrl = ${configuredUrl(fresh)} (already set → left untouched)`); return 0; }
162
+ fresh.notifyUrl = p.url;
163
+ state.saveConfig(fresh);
164
+ out(`📡 notifyUrl seeded: ${p.url} (from ${p.source}) — colab now pushes its events there`);
165
+ return 0;
166
+ }
167
+
168
+ if (require.main === module) process.exitCode = main(process.argv.slice(2));
169
+
170
+ module.exports = { ENDPOINT_FILE, PUSH_ONLY_KINDS, endpointFile, readDeclared, status, healthLine, plan, main };
@@ -257,6 +257,16 @@ function batchGreenCoversTrunk({ trunkRows, batchRows, trunkFires, batchFires })
257
257
  return (batchRows || []).length >= a.length;
258
258
  }
259
259
 
260
+ /**
261
+ * #415: branches the command line names that a staged batch does not carry, in command-line order.
262
+ * `staged` is parseMemberTrailers' `[{ branch }]`. Not a refusal on its own: a branch over the cap or
263
+ * dropped at build is EXPECTED to be missing on resume — the caller must say so, never stay silent.
264
+ */
265
+ function notStaged(requested, staged) {
266
+ const have = new Set((staged || []).map((m) => m && m.branch).filter(Boolean));
267
+ return [...new Set(requested || [])].filter((b) => b && !have.has(b));
268
+ }
269
+
260
270
  /** The clause each member's 🚢 evidence comment gains: which combined run graded it. */
261
271
  function evidenceSuffix({ n, ref, headSha, runIds }) {
262
272
  const runs = (runIds || []).length ? (runIds || []).join(', ') : '(id unread)';
@@ -273,5 +283,5 @@ module.exports = {
273
283
  MAX_BATCH, REF_PREFIX, PROBE_REF, TRAILER_KEY,
274
284
  parseShipBatch, batchRefName, parseBatchRef, memberTrailer, parseMemberTrailers,
275
285
  branchCiClass, memberEligibility, selectMembers, wiring, combinedVerdict, nextStep, foreignBatchStep,
276
- batchGreenCoversTrunk, evidenceSuffix, serialLine,
286
+ batchGreenCoversTrunk, evidenceSuffix, serialLine, notStaged,
277
287
  };